Why asynchronous programming
In the present large-scale high concurrent web application, because of the hardware and the network limit, I/O processing speed is quite slow, often becomes the WEB system performance bottleneck. Node.js through Non-blocking IO and event-driven is a good mitigation of the Web server's resource footprint in high concurrency, greatly improving the Web server's ability to handle high concurrency. At the same time, the lightweight and fast asynchronous programming brought by Node.js brings a fresh air to WEB development. So for the vast number of Java developers, whether a similar WEB development can be implemented, the answer is yes. With the Groovy dynamic language, Jetty, and other lightweight Web servers, it is easy to do asynchronous programming on the Web.
Introduction to Groovy
Groovy is a dynamic language based on a Java virtual machine. Groovy code can be combined nicely with Java code. Provides Java developers with a modern and popular dynamic programming language feature, and the cost of learning is low. The current release is 1.8. The code for our example below is to use this version.
Jetty Introduction
Jetty is a Java-enabled, Open-source, standards-based, and rich-functionality HTTP server and Web container that can be used commercially for free. There are already a lot of successful products that are based on Jetty, such as Apache Geromino, Eclipse, Google appengine, and so on. Jetty can be used as a traditional WEB server or as a dynamic content server, and Jetty can be easily embedded in Java applications. The current version is 8.1. The code for our example below is to use this version.
How to use Jetty to quickly develop lightweight WEB services
Jetty can be easily embedded in an application, just like using a generic class library. The sample code is as follows:
Listing 1. Rapid development of lightweight WEB services with Jetty
Class DefaultHandler extends Abstracthandler {
void handle (String target, Request baserequest,
HttpServletRequest request,httpservletresponse response) {
Response.ContentType = "Text/html;charset=utf-8"
response.status = Httpservletresponse.sc_ok
baserequest.handled = True
response.writer.println "
From the code we can see that instantiating a server object first, and specifying that the port that the server listens on is 8080. Then set up a Handler for the server to process the WEB request, we are here DefaultHandler, and finally call the Start method to start the server. Such a simple WEB server can be used, only a few simple lines of code.
Accessing url:http://localhost:8080 in the browser will get the following response:
Figure 1. Web page Response