Tips for developers: Vert.x – a new generation Java web frameworkJanuary 16th, 2013

Quite recently, there have been several new lightweight Java web frameworks which are becoming more and more popular within the Java developer’s community. It is interesting to notice most of them borrow ideas coming from other ecosystems (Python, Ruby, Scala, Javascript…) and therefore they do not always adopt the usual Web Application Archive paradigm we are used to.

Introducing Vert.x

One of those frameworks is Vert.x

 This framework is the Node.js counterpart in our JVM world… I refer to JVM (Java Virtual Machine) and not only Java, because the framework has been designed to handle applications development with many JVM compatible languages (such as Groovy, Jython or even JRuby)

Like its counterpart Node.js, it supports the reactor pattern but in a slightly improved version called multi reactor : application units (called verticles) can be instanciated on several event loops and since each verticle will always be assigned to the same thread, it simplifies greatly concurrency handling in your application code.

Vert.x provides several nice features such as :

  • Http/Net server implementation
  • Websocket support
  • Can be used standalone or embedded
  • Cluster support thanks to Hazelcast

Vert.x creator, Tim Fox, published a benchmark of Vert.X against Node.js (available here), and even though results were in favor of his project, some developers do not share his opinion because methodology because especially :

  • NodeJs version was not the last one
  • Test client was home made (whereas existing recognized tools could have been used)
  • Client and Server were on the same computer, which is not a good load testing practice

This debate is not going to end soon since Vert.x is still quite young compared to others frameworks.

See Vert.x in action

In my opion, one of the most interesting features is the distributed event bus, which allow you to communicate between your application verticles and even with you browser thanks to SockJs integration.

Here is a dummy implementation of such a concept with a chat application in groovy:

Server side code

def configWebServer = [:];
container.deployVerticle("WebServerVerticle.groovy", configWebServer,4, {});

Here we’ve just asked vertx to deploy 4 instances of verticle WebServerVerticle : this shows another nice feature since you can deploy verticle programmatically in you code. Now let’s see this WebServerVerticle  script in detail :

import org.vertx.groovy.core.http.*

def httpServer = vertx.createHttpServer()
// Web server stuff : provide static files (JS,HTML,...) for browser
def routeMatcher = new RouteMatcher()
routeMatcher.get("/") { req ->
req.response.sendFile("web/index.html")
}
routeMatcher.get("/js/:jsFile") { req ->
def jsFileName = req.params["jsFile"]
req.response.sendFile("web/js/$jsFileName")
}
httpServer.requestHandler(routeMatcher.asClosure())
// Socks JS/EventBus bridge stuff : provide two ways communication
// between browser and server

def config = ["prefix": "/news","session_timeout": 2 * 60 * 1000 ];
def inBound = []
def outBound = []
inBound << ["address":"channel.news"]
outBound << ["address":"channel.news"]
vertx.createSockJSServer(httpServer).bridge(config, inBound, outBound)
// listen at port 4444
httpServer.listen(4444)
 

Notice that :

  • first we are initializing our HTTP server, especially to serve our necessary html and vert.x/sockjs JS files thanks to a routeMatcher
  • then we are initializing our SockJs server with parameters such like url prefix (url part on which our SockJS server will answer) and session_timeout, we are also opening the bridge for inbound and outbound messages on one topic called channel.news
  • eventually we start the server on port 4444

Client side code

For the sake of clarity, I’ve only put the JS content using JQuery API) therefore let’s assume we have a page with :

  • a text input control (identified by postNewsText)
  • a button (identified by postNewsButton)
  • a news list which will contain received messages (identified by newsList)


$(document).ready(function(){

// eventbus initialization : we are pointing at SockJS server prefix defined earlier
//To do so, we are creating a EventBus object
//defined in vertxbus.js (provided by Vert.x)
var topic = 'channel.news';
var eb = new vertx.EventBus('http://localhost:4444/news');
// eventbus handlers
// bus is opened : we register an handler to display message in an HTML list
//when such message is there

eb.onopen = function() {
eb.registerHandler(topic, function(message) {
$("#newsList").append(message.content);
});
}
// bus is closed
eb.onclose = function() {
console.log('bus closed!');
}
// when we click on the button, let's publish text input content on the topic !
$("#postNewsButton").click(function(){
var message = {};
message.content = $("#postNewsText").val();
eb.publish(topic,message);
});
});
 

JS code is self explanatory : when page is loaded, we open event bus and register the event handler to our topic channel.news to append each new message to our news list.

On the other side, when we click on the button, we publish our text input control content on this same topic. This simple demo is obviously more interesting with two or more browsers connected to the event bus ;-)


Share and Enjoy:


Leave a Reply


5 + = twelve