Vert.x 3.4.0.Beta1 release

We have re­leased 3.4.0.Beta1, this re­lease is the biggest since Vert.x 3.0.0 with plenty of great fea­tures.

You can use con­sume it in your projects from Maven or Gra­dle as usual with the ver­sion 3.4.0.Beta1 or read

Let me out­line the im­por­tant changes you can al­ready find in this Beta1.

Vert.x Web Client

In a sim­ple sen­tence “Vert.x Web Client is to Vert.x Http­Client what Vert.x Web is to HttpServer”

The Web Client makes it easy to do HTTP re­quest/re­sponse in­ter­ac­tions with a web server, and pro­vides ad­vanced fea­tures like:

  • Json body en­cod­ing / de­cod­ing
  • re­quest/re­sponse pump­ing
  • re­quest pa­ra­me­ters
  • uni­fied error han­dling
  • form sub­mis­sions
  • and more!

Built on top of Http­Client, it nat­u­rally in­her­its its fea­tures and pro­vides a bet­ter API, let me give an overview in one ex­am­ple:

WebClient client = WebClient.
client
  .get(8080, "myserver.mycompany.com", "/some-uri")
  .as(BodyCodec.json(User.class))
  .send(ar -> {
    if (ar.succeeded()) {

      HttpResponse<User> response = ar.result();
      User user = response.body();

      System.out.println("Received response with status code" + response.statusCode() + " with body " +
        user.getFirstName() + " " + user.getLastName());
    } else {
      System.out.println("Something went wrong " + ar.cause().getMessage());
    }
  });

RxJava singles

Rx­Java is a very pop­u­lar Java ex­ten­sion and in this re­lease we fo­cused on the API us­abil­ity with the sup­port of the Single Rx­Java type.

The new meth­ods are pre­fixed by rx and dep­re­cates the Observable suf­fixed meth­ods.

So in­stead of start­ing a server with listenObservable now you use rxListen:

HttpServer server = vertx.createHttpServer();
Single<HttpServer> single = server.rxListen(8080, "localhost");
single.subscribe(
  ok -> System.out.println("Server started"),
  err -> System.out.println("Something went wrong " + err.getMessage()));

One no­tice­able dif­fer­ence with the pre­vi­ous API, is that the listen method is called when the Single is sub­scribed.

This is very handy when com­bined with the new web client:

Single<HttpResponse<Buffer>> single = client
  .get(8080, "myserver.mycompany.com", "/some-uri")
  .rxSend();

// Send the request
single.subscribe(response -> System.out.println("got response " + response.statusCode());

// Send the request again
single.subscribe(response -> System.out.println("got response " + response.statusCode());

Polyglot

In this beta you can try Vert.x for Kotlin.

Vert.x for Kotlin is based on the Java API and pro­vides also the ex­e­cu­tion of Kotlin Ver­ti­cles.

import io.vertx.core.*
import io.vertx.kotlin.core.http.HttpServerOptions

class Server : AbstractVerticle() {

  override fun start() {
    vertx.createHttpServer(

        // We provide Kotlin extension methods, allowing to use an idiomatic Kotlin API for building these options
        HttpServerOptions(
            port = 8080,
            host = "localhost"
        ))
        .requestHandler() { req ->
          req.response().end("Hello from Kotlin")
        }
        .listen()
    println("Server started on 8080")
  }
}

It can be di­rectly ran from the com­mand line:

julien:vertx-kotlin-example julien$ vertx run Server.kt
Server started on 8080
Succeeded in deploying verticle

As you can see, Kotlin is using the Java API di­rectly, and we thought that it might be a cool thing to do the same with Groovy sup­port. So we have re­con­sid­ered our Groovy sup­port and now it uses the plain Java API, with­out los­ing the ex­ist­ing fea­tures.

Thanks to Groovy ex­ten­sion meth­ods, id­iomatic Groovy is still sup­ported while ben­e­fit­ing from the full Java API!

Scala sup­port is also planned for 3.4.0 and will be re­leased soon, watch @vertx_project.

The microservices story goes on…

Our APIs have ma­tured and now they have been moved out of tech pre­view, of course this wasn’t enough and we now have Vert.x Con­fig, an ex­ten­si­ble way to con­fig­ure Vert.x ap­pli­ca­tions sup­port­ing File, json, ENV, sys­tem prop­er­ties, HTTP, Ku­ber­netes Con­figmap, Con­sul, Spring Con­fig Server, Redis, Git, Zookeeper, … stores as well as sev­eral for­mats: prop­er­ties file, YAML and Hocon.

Here is a small ex­am­ple:

ConfigStoreOptions httpStore = new ConfigStoreOptions()
  .setType("http")
  .setConfig(new JsonObject()
    .put("host", "localhost").put("port", 8080).put("path", "/conf"));

ConfigStoreOptions fileStore = new ConfigStoreOptions()
  .setType("file")
  .setConfig(new JsonObject().put("path", "my-config.json"));

ConfigStoreOptions sysPropsStore = new ConfigStoreOptions().setType("sys");

ConfigRetrieverOptions options = new ConfigRetrieverOptions()
  .addStore(httpStore).addStore(fileStore).addStore(sysPropsStore);

ConfigRetriever retriever = ConfigRetriever.create(vertx, options);

Vert.x Con­fig also sup­ports push based no­ti­fi­ca­tion style:

ConfigRetriever retriever = ConfigRetriever.create(Vertx.vertx(), options);
retriever.configStream()
  .endHandler(v -> {
    // retriever closed
  })
  .exceptionHandler(t -> {
    // an error has been caught while retrieving the configuration
  })
  .handler(conf -> {
    // the configuration
  });

Vertx MQTT Server

Vert.x MQTT Server is able to han­dle con­nec­tions, com­mu­ni­ca­tion and mes­sages ex­change with re­mote MQTT clients. Its API pro­vides a bunch of events re­lated to pro­to­col mes­sages re­ceived by clients and ex­poses allow to send mes­sages to them.

Here is a small ef­fec­tive ex­am­ple of cre­at­ing, the Vert.x way!

MqttServerOptions options = new MqttServerOptions()
  .setPort(1883)
  .setHost("0.0.0.0");

MqttServer server = MqttServer.create(vertx, options);

server.endpointHandler(endpoint -> {

  System.out.println("connected client " + endpoint.clientIdentifier());

  endpoint.publishHandler(message -> {

    System.out.println("Just received message on [" + message.topicName() + "] payload [" +
      message.payload() + "] with QoS [" +
      message.qosLevel() + "]");
  });

  endpoint.accept(false);
});

server.listen(ar -> {
  if (ar.succeeded()) {
    System.out.println("MQTT server started and listening on port " + server.actualPort());
  } else {
    System.err.println("MQTT server error on start" + ar.cause().getMessage());
  }
});

Vert.x SQL streaming

We now sup­port stream­ing style for SQL queries:

connection.queryStream("select * from test", stream -> {
  if (stream.succeeded()) {
    SQLRowStream sqlRowStream = stream.result();

    sqlRowStream
      .handler(row -> {
        // do something with the row...
        System.out.println(row.encode());
      })
      .endHandler(v -> {
        // no more data available, close the connection
        connection.close(done -> {
          if (done.failed()) {
            throw new RuntimeException(done.cause());
          }
        });
      });
  }
});

And with the Rx­Java API:

client
  .rxGetConnection() // Connect to the database
  .flatMapObservable(conn -> { // With the connection...
    return conn.rxUpdate("CREATE TABLE test(col VARCHAR(20))") // ...create test table
      .flatMap(result -> conn.rxUpdate("INSERT INTO test (col) VALUES ('val1')")) // ...insert a row
      .flatMap(result -> conn.rxUpdate("INSERT INTO test (col) VALUES ('val2')")) // ...another one
      .flatMap(result -> conn.rxQueryStream("SELECT * FROM test")) // ...get values stream
      .flatMapObservable(sqlRowStream -> {
        return sqlRowStream.toObservable() // Transform the stream into an Observable...
          .doOnTerminate(conn::close); // ...and close the connection when the stream is fully read or an error occurs
      });
  }).subscribe(row -> System.out.println("Row : " + row.encode()));

Finally

In ad­di­tion to all these bril­lant fea­tures here is a list of more-​than-noticeable things you have in this Beta1:

  • Vert.x In­fin­is­pan re­places Vert.x Jgroups clus­ter man­ager
  • Vert.x Con­sul Client pro­vides a full fledged client for Con­sul
  • Oauth2 pre­de­fined con­fig­u­ra­tion with 16 set­tings from Azure Ac­tive Di­rec­tory, to Twit­ter with the usual sus­pects (Face­book, LinkedIn, …)
  • Http client now fol­low redi­rects

You can use and con­sume it in your projects from Maven or Gra­dle as usual with the ver­sion 3.4.0.Beta1 or read

Last but not least, I want to per­son­ally thank all the peo­ple that con­tributed to this re­lease, be­yond the Vert.x core team, the ac­tual Vert.x com­mit­ters and many other peo­ple who have given a lot of ef­fort to this up­com­ing 3.4.0!!!!

Next post

Vert.x 3.4.0 is released!

Vert.x 3.4.0 has just been released with many new exciting features!

Read more
Previous post

An Introduction to the Vert.x Context Object

Under the hood, the vert.x Context class plays a critical part in maintaining the thread-safety guarantees of verticles. Most of the time, vert.x coders don't need to make use of Context objects directly.

Read more
Related posts

Things to keep in mind concerning CSRF attacks

Eclipse Vert.x like most frameworks provides an anti-CSRF defense. However, no framework can prevent all attack vectors that exist in the web. Therefore, developers need to be aware of some dangers and common attack vectors concerning CSRF defenses.

Read more

Real-time bidding with Websockets and Vert.x

The expectations of users for interactivity with web applications have changed over the past few years. Users during bidding in auction no longer want to press the refresh button.

Read more

Some Rest with Vert.x

This post is part of the Introduction to Vert.x series. Let’s go a bit further this time and develop a CRUD-ish application

Read more