Cheat Sheet: Eclipse Vert.


Table of Contents

1. Introduction 1 4. Timer and Periodic Tasks 6
1.A Reactive Systems 1 5. HTTP 6
1.B Programing with Vert.x 2 5.A HTTP Server 6
2. Create a new Vert.x application 2 5.B HTTP Client 7
2.A Create a Vert.x application 6. EventBus 8
with Apache Maven 3 6.A Point to Point 8
2.B Create a Vert.x application 6.B Publish/Subscribe 8
with Gradle 3 6.C Request-Response 9
2.C Create a Vert.x application 6.D Delivery Options 10
with the Vert.x CLI 3 7. Executing blocking code 10
3. Verticles 4 7.A Execute blocking construct 10
3.A Creating a verticle 4 7.B Worker verticles 11
3.B Deploying verticles 8. Executing Vert.X applications 12
programmatically 5 9. Further learning 13
3.C Configuring verticles 5 10. About the author 13

1. Introduction

Eclipse Vert.x is a toolkit to build reactive and distributed systems. Application using Vert.x
are fast, responsive, resilient and elastic. Vert.x is incredibly flexible - whether it’s network
utilities, modern web applications, microservices, or a full blown back-end message-bus
application, Vert.x is a great fit.

Vert.x is event driven and non blocking. This means your app can handle a lot of
concurrency using a small number of threads. Vert.x applications run on top of the Java
Virtual Machine but can be implemented in many language such as Java, JavaScript, Groovy,
Ruby and Ceylon. Vert.x provides idiomatic APIs for every supported language.
Vert.x is not a restrictive framework or container, it gives you useful bricks and let you
create your app the way you want to.

1.A Reactive systems

Applications developed with Vert.x are reactive. The
Reactive Manifesto ( defines a
reactive application as having four key properties:
- Use asynchronous message-passing Elastic Resilient
- Elastic Message-driven
- Resilient
- Responsive
Components forming your Vert.x application interact using asynchronous message pass-
ing regardless of whether these components are co-located or distributed. Each component
reacts to the received message by using an asynchronous non-blocking development model.


you will usually provide a Handler to receive events some time later. In most cases Vert. and implement recovery strategies easily.response(). an event loop can deliver a huge quantity of events in a short amount of time.x block the calling thread. It continues to provide its service in a timely-fashion even when the system is facing failures or peak of demand. isolate them. This allows the application to more effectively share resources by doing work only in re- sponse to outside messages.x works differently here. 1.x APIs. You handle these events by providing handlers to the Vert.x APIs are non blocking and won’t block the event loop. Vert.requestHandler(request -> { // This handler will be called every time an HTTP request is // received at the server request. hence the golden rule: Don’t block the event loop. This is called the Reactor pattern.x applications are resilient. This pattern is called Multi-Reactor Pattern.x is a toolkit.x calls your handlers using a thread called an event loop. In a standard reactor implementation there is a single event loop thread which runs around in a loop delivering all events to all handlers as they can face failures. giving you a great freedom to use your favorite tool. to receive an HTTP request event: server. meaning they react to increasing load well. Vert. none of the APIs in Vert.x notifies you by sending events. Create a new Vert. The final property. but that’s not much help if you block the event loop yourself in a handler. this means that when things happen in Vert. Instead of a single event loop. 2.x that you are interested in.x applications are largely event driven. If a result can be provided immediately. As Vert. it can also be embedded in your Spring or JavaEE applica- tion too. The trouble with a single thread is it can only run on a single core at any one time. 2 . means the application is real-time and engaging.x applications are also elastic. and the vertx CLI. because the architecture highly concurrent and distributed.x application There are many ways to create a Vert.B Programming with Vert.x application. each Vertx instance maintains several event loops. treating failure as a first-class citizen --. Gradle. Vert. Because noth- ing blocks. Vert. With very few exceptions. In this cheat sheet. That means you can handle a highly concurrent work load using a small number of threads. otherwise. }).end(“hello world”). For example. responsive. it will be returned. Vert. we will demonstrate three ways to create projects with Apache Maven.x Vert.

/redeploy.x CLI git clone https://github.core. Add the dependency in the gradle.Launcher” from http://localhost:8080 Use vertx./gradlew run changes recompile and restart the applica- tion.bat on Windows 3 .bat mvn package Package An executable fat jar is created in the target directory.A Create a Vert.vertx. Add the dependency in the pom.project Dependency management file You need to restart gradlew to reflect the changes Import the project as a Gradle project in your IDE support favorite IDE 2. The started application is accessible --launcher-class=” Generate and Run vertx-cli-starter.C Create a Vert.git PROJECT_NAME the application in redeploy mode: your cd PROJECT_NAME changes recompile and restart the .com/vert-x3/ Generate and Run vertx-gradle-starter.git PROJECT_NAME It generates the project structure and start cd PROJECT_NAME the application in redeploy mode: your .sh run src/io/vertx/starter/ changes recompile and restart the applica- MainVerticle.x application with the Vert.x application with Apache Maven Command Description # Linux and MacOS Generate and Run git clone vertx-maven-starter.git PROJECT_NAME It generates the project structure and start cd PROJECT_NAME the application in redeploy mode: your .sh application./gradlew shadowJar Package An executable fat jar is created in the build/libs directory. The started application # Windows is accessible from http://localhost:8080 git clone https://github.git PROJECT_NAME cd PROJECT_NAME --redeploy=”src/**/*” tion.x application with Gradle git clone It generates the project structure and start vertx-maven-starter. The started application is accessible from http://localhost:8080 .xml file Dependency management Add the dependency in the pom./vertx.B Create a Vert.xml file Import the project as a Maven project in your IDE support favorite IDE 2.

requestHandler({ req -> req.requestHandler(req -> req. add the indicated dependency to your project: Language Dependency to add to your project Verticle Java N/A ( resolve Import the project as a Java project.createHttpServer() . Verticles can be implemented in any supported lan- guage.requestHandler(function (req) { req.vertx::vertx-lang-js vertx. Command Description Edit the vertx/vertx-stack. Default verticles are executed on the Vert.x event loop and must never block. . that starts a HTTP server. You need to restart the application to reflect Then. 3. Vert./vertx.response().createHttpServer() .json to add.A Creating a verticle All the projects created with the given instructions have created a main verticle.end(“Hello from Groovy”) }) . Add the IDE support vertx/lib directory in your classpath.x en- sures that each verticle is always executed by the same thread (never concurrently. 4 .x comes with a simple. response() . Verticles are chunks of code that get deployed and run by Vert. hence avoiding synchronization constructs).listen(8080).createHttpServer() . An application would typically be composed of many verticle instances running in the same Vert.end(“Hello from Java”)) .x. actor-like deployment and concurrency model out of the box. } } Groovy io. Verticle instances communicate with each other by sending messages on the event bus. Verticles Vert. provided) public class MyHttpServer extends AbstractVerticle { @Override public void start() throws Exception { vertx.x instance at the same time. implement- ed in Java. 3. run: the changes.listen(8080).response(). and to add support for another language. scalable.listen(8080) JavaScript io. Dependency management remove or update your dependency.end(“Hello from JavaScript”) }) .vertx::vertx-lang-groovy vertx.

deployVerticle(“verticles/my-verticle. new DeploymentOptions() . MyVerticle.deployVerticle(“verticles/MyVerticle.deployVerticle(MyVerticle. “value”))).js”).config()[“key”]).js”.deployVerticle( println(config().class. vertx. you can also use the fully qualified class name (FQCN).deployVerticle( getOrCreateContext() “verticles/my-verticle. (Vert.”). 3. You can also provide the verticle configura- tion.) Language Verticle Deployment Java System.B Deploying verticles programmatically Verticles can be deployed programmatically from your code. “verticles/my-verticle.groovy”.put(“key”. Verticles deployed in this manner are identified using the verticle file name. {“config”: {“key”: “value”}}).deployVerticle(“verticles/my-verticle. 3.class.deployVerticle( getOrCreateContext().C Configuring verticles When deploying a verticle. Groovy println(vertx. } } Groovy vertx. config()[‘key’]) [‘config’: [‘key’: ‘value’]] ) JavaScript console.js”). .log(vertx. For a Java verticle.deployVerticle(“verticles/MyVerticle.groovy”) vertx.deployVerticle(“verticles/my-verticle. getString(“key”)).deployVerticle(“verticles/my-verticle.groovy”). This pattern is often used by a main verticle deploying sub-verticles. vertx.deployVerticle(“verticles/my-verticle. vertx. Verticles can also have an optional stop method that is called when the verticle is unde- ployed. The stop and corresponding start methods can also take a Future object as parameter to start and stop asynchronously. 5 . vertx. Language Verticle Java public class MainVerticle extends AbstractVerticle { @Override public void start() { vertx.x uses JSON as configuration” vertx. or high-availability mode.getName().deployVerticle(“verticles/my-verticle. you can pass deployment options to configure things such as the number of instances. vertx.out.groovy”).getName()). vertx.js”) JavaScript vertx.setConfig(new JsonObject() .

“text/html”) .deployVerticle( -> { MyVerticle.out.cancelTimer(taskId) JavaScript vertx.result().4.println(“Server started on port “ + ar.put(“key”.setPeriodic(2000. getMessage()). vertx. { l -> println(“Run { l -> println(“Run periodically”)}) later”)}) //. HTTP This section contains examples to creates Vert.out.. function (l) { function (l) { console. var taskId = vertx. . def taskId = vertx.cause(). } }).getName()..cancelTimer(taskId).log(“Run console.class. }).createHttpServer() . l vertx. }). Timer and periodic tasks Vert. //.setTimer(1000. 5. Groovy vertx.requestHandler(req -> req.. vertx.setTimer(1000.end(“<h1>Hello from Java</h1>”)) .setTimer(1000. . 5. actualPort()). “value”))).x HTTP servers and client.A HTTP Server Language Verticle Java public class MyHttpServer extends AbstractVerticle { @Override public void start() throws Exception { vertx.setConfig(new JsonObject() }).response() .log(“Run periodically”) later”).println(“Run new DeploymentOptions() later”).x lets you execute delayed tasks and periodic tasks.out.setPeriodic(2000. } } } 6 . System.putHeader(“content-type”. } else { System.println(“Unable to start server “ + ar.listen(8080.succeeded()) { System.. ar -> { if (ar. Language Verticle Deployment Java vertx.

}). { resp -> println(“Response ${resp. “/”.statusCode()}”) resp. “localhost”.requestHandler(function (req) { req. “text/html”) . } else { println(“Unable to start server “ + ar.Language Verticle Groovy vertx.result(). response -> { System. “localhost”.listen(8080.out. getMessage()).createHttpServer() . resp.end(“<h1>Hello from JavaScript</h1>”) }) . function(res. “/”.response().bodyHandler(function (body) { console.createHttpClient(). 7 . } }).putHeader(“content-type”.get(8080. “localhost”.requestHandler({ req -> req. }).response() .actualPort()).log(“Unable to start the HTTP server: “ + err. “/”.succeeded()) { println(“Server started on port “ + ar.createHttpClient().log(“Response “ + resp.out. { ar -> if (ar.end(). err) { if (err) { console.bodyHandler({ body -> println(“Data ${body}”) }) }).listen(8080.statusMessage()).actualPort()). 5.end(). “text/html”) .end(“<h1>Hello from Groovy</h1>”) }) . } }) JavaScript vertx. } else { console.get(8080.putHeader(“content-type”.cause().createHttpServer() .println(“Data: “ + buffer.B HTTP Client Java public class MyHttpClientVerticle extends AbstractVerticle { @Override public void start() { vertx. function (resp) { console.toString()) ).get(8080.log(“Data “ + body).statusCode()). }) .println(“Response: “ + response. } } Groovy vertx. response.bodyHandler(buffer -> System.log(“Server started on port “ + res.end() JavaScript vertx.createHttpClient().getMessage()).

vertx.eventBus(). console.eventBus().setPeriodic(1000.println(“Received: “ + message.send(“address”.send(“address”. }). console. }). 6.body()).body()). var eb = vertx.publish(“address”. EventBus The event bus is the backbone of any Vert.consumer(“address”. Groovy vertx. message. function { (message) { eb.body())). The event bus offers three methods of delivery: point to point. { v -> vertx.eventBus() message -> . Consumers listen for messages by registering a Handler on a specific address. function (v) eb. vertx. “my message”)).consumer(“address”.eventBus(). “my message”) {“config”: {“key”: “value”}}). “my message”). { message -> “my broadcasted message”) println(“Received: ${message. System.setPeriodic(1000. }) JavaScript var eb = vertx. v -> vertx. System. function { (message) { eb. 8 . publish/subscribe.js”.setPeriodic(1000. 6. { v -> vertx.consumer(“address”. regardless of the implementation language and their local- ization. “my message”)).eventBus().eventBus() message -> .eventBus(). }) body()}”) }) JavaScript var eb = vertx. vertx.eventBus().log(“Received: “ + “my broadcasted message”).out. and request-response. function (v) eb. It allows the components compos- ing your application to interact.eventBus().deployVerticle( vertx.send(“address”.A Point to Point Language Sender Verticle (send a message every Deployment second) Java vertx.setPeriodic(1000. var eb = vertx.body())).log(“Received: “ + }).6.consumer(“address”.B Publish/Subscribe Java vertx. “verticles/my-verticle. messages are sent to addresses.println(“Received: “ + message.eventBus(). An address is a simple String. message.setPeriodic(1000.consumer(“address”.send(“address”.out. On the event bus. vertx. vertx.x application.setPeriodic(1000.publish(“address”.eventBus(). Groovy vertx. }). v -> vertx.

succeeded()) { message. System. the reply handler receives a failed result).reply(“my response”).consumer(“address”. function (v) { function (message) { eb.out. }). } else { console. console. vertx. message. . For example. function (reply. you can pass the sending time or an identifier using a header.succeeded()) { body()}”) println(“Response: ${reply.body()).out.out.body()). + reply.send(“address”. if (reply.eventBus(). } }). v -> vertx.eventBus().consumer(“address”. 9 .reply(“my if (reply_err == null) { response”). var eb = vertx.The codec name to serialize the message on the event bus (only required for non supported types).eventBus().log(“Response: }).setPeriodic(1000. { v -> vertx.consumer(“address”.D Delivery Options When sending or publishing a message on the event bus.setPeriodic(1000. { reply -> println(“Received: ${message. “ + reply. Groovy vertx.6.C Request-Response Language Sender Verticle (send a message every Deployment second) Java vertx.The message headers than can be used to pass metadata about the message content to the consumers.println(“Response: “ }). “my console. + message. . eb.println(“No reply”).send(“address”.println(“Received: “ reply -> { + message. 6.body()). System.body()). vertx.log(“No reply”).eventBus(). if (reply.send(“address”.log(“Received: “ message”. } else { System.The send timeout (if the receiver does not reply to the message.reply(“my response”) body()}”) }) } else { println(“No reply”) } }) }) JavaScript var eb = vertx.setPeriodic(1000. vertx. you can pass delivery options to configure: . “my message”. { message -> “my message”.eventBus(). } })).result(). reply_err) { message.result().eventBus() message -> { .

complete(“my result”).result()) // The blocking has completed successfully } else { // The blocking code has failed } } ). // Example of failure: future. Language Verticle Java“failure cause”). The executeBlocking method takes two functions as parameters: the first one is run on a worker thread.x provides two ways to execute blocking code: vertx.executeBlocking( { future -> // Run some blocking code on a worker thread // Complete or fail the future once done future. 10 .7. { ar -> // Run on the event loop if (ar. ar -> { // Run on the event loop if (ar. }.executeBlocking and Worker verticles.succeeded()) { println(ar. Groovy vertx. Vert. the second function is executed on the event loop once the first function has com- pleted the provided Future object. Executing blocking code As mentioned above.<String>executeBlocking( future -> { // Run some blocking code on a worker thread Language // Complete or fail the future once done future.A The “executeBlocking” construct The executeBlocking construct lets you execute blocking code directly in your code.succeeded()) { // The blocking has completed successfully } else { // The blocking code has failed } } ).complete(“my result”) // Example of failure: future. 7. you must not run blocking code on the event“failure cause”) }.

use deployment options as follows: Java public class MainVerticle extends AbstractVerticle { @Override public void start() { vertx. This Launcher is convenient but not mandatory --. Language Verticle JavaScript vertx.jar verticle -cluster -cluster -cp Add items to the vertx run my.:.getName(). new DeploymentOptions(). 7. [worker: true]) 8. [worker: true]) JavaScript vertx.executeBlocking( function (future) { // Run some blocking code on a worker thread // Complete or fail the future once done future. you can implement your own main class. // The blocking has completed successfully } else { // The blocking code has failed } } ). Executing Vert. function (res.deployVerticle(“verticles/MyWorkerVerticle./ -cp .setWorker(true)). // Example of failure: future. }.jar classpath verticle -cp . java -jar my-fat. but instead by a worker thread. Workers are not exe- cuted on the”. the execution can be configured: Parameter Description Example with the Example with a fat jar vertx CLI -cluster Enable cluster mode vertx run my./conf conf 11 .deployVerticle(“verticles/MyWorkerVerticle.x applications Both the vertx CLI and the fat-jar created in the generated projects use the same Launcher. } } Groovy vertx. err) { // Run on the event loop if (err == null) { console.log(res).x event loop.class. java -jar my-fat. When using the”.deployVerticle(“failure cause”).B Worker verticles A worker verticle is a specialized verticle that can run blocking code.complete(“my result”). To mark a verticle as worker.

Vert. Kafka and legacy applications (using Apache Camel).http://vertx. the execution can be configured: start Start an application vertx start java -jar my-fat. Clement is an active contributor on many open source projects such as Apache Felix.json given json file . from academic positions to management.jar in background my-verticle -id start -id my-service my-service list List all Vert.x also provides components such as Vert.x Web to build modern web applications. mobile.jar applications list launched in background stop Stop an application vertx stop java -jar my-fat./ jar -ha availability mode conf --conf=x Configure the main vertx run my.http://vertx.x. continuous delivery.x ecosystem --. java -jar 10. He has experience with many domains and technologies. such as: OSGi. instance in . About the author Clement Escoffier is Principal Software Developer at Red Hat. Further learning This cheat sheet covers just a small part of the Vert. and more.jar verticle with the verticle --conf=my. iPOJO. circuit breaker…).jar launched in my-service stop my-service background 9. java -jar my-fat.x vertx run my. It provides components to build microservices (service discovery.json When using the Launcher. java -jar my-fat.jar instances as verticle -cluster --instances=2 specified of the main verticle -ha launch the vert. Eclipse Vert. 12 . --conf=my-conf.x vertx list java -jar my-fat.http://vertx. Wisdom Framework. Clement has had several professional lives. a set of bridges and clients to interact with AMQP. Parameter Description Example with the Example with a fat jar vertx CLI --instances=x Create as many vertx run my.:. and obviously. RPC interactions. and devops. MQTT. Learn more about this ecosystem on: . verticle -cp .