Vert.x Handlers

Let's do an exercise to better understand Handlers in Vert.x

Handlers

A handler in Vert.x is a form of Callback. Handlers are passed as arguments to some Vert.x methods so that the callback can be executed once a particular asynchronous operation has been completed. Handlers for Vert.x can be written in Groovy in several ways:
Exercise 1: Handler classes

The basic Handler in Vert.x is any class which implements the Handler interface. For example:

Exercise1.groovy
import io.vertx.lang.groovy.GroovyVerticle
import io.vertx.core.json.JsonObject

class Exercise1 extends GroovyVerticle {

    private class RequestHandler implements Handler {
        void handle(HttpServerRequest req) {
            def response = new JsonObject([ok: true]).encode()
            req.response().end(response)
        }
    }

    void start() {
        // Create a JSON response
        def response = new JsonObject([ok: true]).encode()

        vertx.createHttpServer()         // Create a new HttpServer
             .requestHandler(new RequestHandler())
             .listen(8080, '127.0.0.1')  // Listen on port 8080 and interface `127.0.0.1`
    }
}
As you can see, we pass an instance of the RequestHandler class to the requestHandler() method on the HttpServer object and that instance will handle the HTTP requests.
Exercise 2: Method References

Another way to implement handlers removes some of the boiler-plate of having a separate hanlder class for each Callback we want to register. It’s called a Method Reference. A method reference is a way of assigning a method to behave as a callback without having to implement a Handler interface on a new class.

Exercise2.groovy
import io.vertx.groovy.core.http.HttpServerRequest
import io.vertx.lang.groovy.GroovyVerticle
import io.vertx.core.json.JsonObject

class Exercise2 extends GroovyVerticle {

    /**
     * Handle HttpServerRequests
     */
    void handleRequest(HttpServerRequest req) {
        def response = new JsonObject([ok: true]).encode()
        req.response().end(response)
    }

    void start() {
        // Create a JSON response
        def response = new JsonObject([ok: true]).encode()

        vertx.createHttpServer()         // Create a new HttpServer
             .requestHandler(this.&handleRequest) // Register a request handler
             .listen(8080, '127.0.0.1')  // Listen on port 8080 and interface `127.0.0.1`
    }
}

Exercise 3: Closures

Finally, in Groovy we can use Closures. Closures are a way of writing a bit of code which can be passed as a value . . . in-line…

Exercise3.groovy

import io.vertx.lang.groovy.GroovyVerticle
import io.vertx.core.json.JsonObject

class HelloWorld extends GroovyVerticle {

    void start() {
        // Create a JSON response
        def response = new JsonObject([ok: true]).encode()

        vertx.createHttpServer()         // Create a new HttpServer
             .requestHandler({ req ->    // Register a request handler
                 req.response().end(response)
             })
             .listen(8080, '127.0.0.1')  // Listen on port 8080 and interface `127.0.0.1`
    }
}
An alternate way of declaring that closure would be to assign the closure to a variable and then pass the variable into the requestHandler() method as shown below:

Exercise3_1.groovy
import io.vertx.core.json.JsonObject
import io.vertx.groovy.core.http.HttpServerRequest
import io.vertx.lang.groovy.GroovyVerticle

class Exercise3_1 extends GroovyVerticle {

    void start() {

        def reqHandler = { HttpServerRequest req ->
            // Create a JSON response
            def response = new JsonObject([ok: true]).encode()
            req.response().end(response)
        }

        vertx.createHttpServer()         // Create a new HttpServer
             .requestHandler(reqHandler) // Register a request handler
             .listen(8080, '127.0.0.1')  // Listen on port 8080 and interface `127.0.0.1`
    }
}
Next Steps: (see HttpServerRequest)


Modify the example above to include the requested path as an item in the JSON response body


Modify the example above to include the request headers as a nested JSON object within the response body

If you want to skip ahead, there are more of these exercises available HERE

Comments

best essay said…
Thank you so much Bro for this valuable and useful information. I was looking for such kind of examples to practice. Keep posting more stuff like that.

Popular Posts