SlideShare a Scribd company logo
1 of 57
Download to read offline
Introducing Vertx
By: Vijay Shukla & Vishal Sahu
Agenda
1. Introduction
2. Main Component
3. Threading and Programming Model
4. Installation
5. Event Bus
6. Verticle
7. Services
8. Templates
Introduction
● Vert.x is a toolkit or platform for implementing reactive applications on the
JVM.
● Vert.x is an open-source project at the Eclipse Foundation. Vert.x was initiated
in 2012 by Tim Fox.
● General Purpose Application Framework
● Polyglot (Java, Groovy, Scala, Kotlin, JavaScript, Ruby and Ceylon)
● Event Driven, non-blocking
● Lightweight & fast
● Reusable modules.
vertx.createHttpServer().requestHandler({ req
->
req.response()
.putHeader("content-type", "text/plain")
.end("Hello from Vert.x!")
}).listen(8080)
Hello World
Main Components
1. Verticles - the building blocks
2. Event Bus & Event Loop
3. Future
4. Routes
Threading and Programming Model
1. The synchronous I/O threading model are simple to understand, but it hurts
scalability with too many concurrent connections.
2. Operating System spends significant time just on thread scheduling management.
3. The unit of deployment in Vert.x is called a Verticle. A verticle processes incoming
events over an event-loop.
4. Event-loops are typical in asynchronous programming models.
5. Every loop is attached to a thread. By default Vert.x attaches 2 event loops per CPU
core thread.
6. The direct consequence is that a regular verticle always processes events on the
same thread, so there is no need to use thread coordination mechanisms to
manipulate a verticle state
7. Verticles run in single thread mode.
8. A verticle is only ever executed by a single thread, and always by the same
thread.
9. It is capable of using all the CPUs in machine, or cores in CPU.
10. It does this by creating one thread per CPU.
11. Each thread can send message to multiple verticles.
12. Verticles are event driven and are only running when receiving message, so a
verticles does not need to have its own exclusive thread.
Comparison of Performance When Only 200/OK Response Has Been Returned.
Comparison of Performance When a 72-byte Static HTML File is Returned.
Event Loop
Installation
Download Minimal Distribution or Full Distribution
Vertx Command Line
The vertx command is used to interact with Vert.x from the command line. Download
and set PATH environment variable. (Make sure Java 8 installed and used)
vertx run my-verticle.groovy
OR
vertx run groovy:com.nexthoughts.MyGroovyVerticle
Dependency Management
Create Vertx Instance
You can create a Vertx instance by calling Vertx.vertx().
1. The Vertx instance creates a number of threads internally to handle the
exchange of messages between verticles.
2. These threads are not daemon threads, so they prevent the JVM from shutting
down, event of the main thread creating the Vertx instance terminates.
3. When creating the Vertx Object you can also provide options if the default is
not right for you.
4. The VertxOptions object has many settings and allows you to configure things
like clustering, high availability, pool sizes etc.
Event Bus - Introduction
1. Verticles are event driven, meaning they do not run unless
they receive a message.
2. Verticles can communicate with each other via the Vert.x
event Bus.
3. Message can be simple objects (e.g. Java Objects), Strings, CSV, JSON, binary
data or whatever else you need.
4. Verticles can send and listen to addresses.
5. An address is like a named channel.
6. When a message is sent to a given address, all verticles that listen on that
address receive the message.
7. Verticles can subscribe and unsubscribe to address without the ender
knowing.
8. This results in a very loose coupling between message senders and message
receivers.
Using The Event Bus
Is is very common for verticles to either listen for incoming messages from the event
bus, or to write messages to other verticles via the event bus.
Listening for Message
1. When a verticle wants to listen for message from the bus, it listen on certain
address. An address is just a name.
2. Multiple verticles can listen for messages on the same address and multiple
verticles can send messages to an address.
3. A verticle can obtain a reference to the event bus via the vertx instance inherited
from AbstractVerticle
Registering Handlers
1. When a message arrives for your handler, you handler will be called, passing in the
message.
2. The object returned from call to consumer() is an instance of MessageConsumer.
3. When registering a handler on a clustered event bus, it can take some time for the
registration to reach all nodes of the cluster. You can register/unregister a
completion handler to be notified.
Publishing/Sending Message
eventBus.publish(“address”,”Send Some message here”)
eventBus.send(“address”,”Send Some message here”)
Sending a message will result in only one handler registered at the address receiving
the message. You can also send message on event bus with headers.
def options=[headers:[“some-header-key”:”some-header-value”]]
vertx.eventBus().send(“address”,”Some Message to be sent”,options)
To acknowledge that the message has been processed the consumer can reply to the
message by calling reply.
Verticles
1. Introduction
2. Create Verticle
3. Start and Stop Verticle Asynchronous
4. Accessing Vert.x instance from Verticle
5. Vert.x type
a. Standard
b. Worker
c. Multi-Threaded
6. Deployment Verticle Programmatically
7. Rules for mapping verticle instance to Verticle Factory.
Introduction
Vert.x can deploy and execute components called Verticles.
A Verticle can be passed some configuration (e.g, credentials, network addresses, etc).
1. Incoming network data can be received from accepting threads then passed as events to
corresponding Verticles.
2. If the Verticle deployed more than once, then the events are being distributed to verticles
instances in a round-robin fashion.
1. The Vertx instance by itself doesn’t do much except all thread management, creating an
event bus etc.
2. In order to get the application to do something useful, you need to deploy one or more
verticles (component) inside the Vertx instance.
3. Before you can deploy a verticles you need to create it.
4. You can create a verticle by extending a class AbstractVerticle.
5. A verticle has a start() and a stop() method which are called when the verticles is
deployed and undeployed respectively.
6. Perform any necessary initialization work inside the start() and necessary cleanup in
stop().
Create Verticle
An application would typically be composed of many verticle instances running in the
same Vert.x instance at same time.
The different Verticle Instance communicate with each other by sending message on the
event bus.
Two alternatives to create verticles:
1. A plain groovy script
2. A groovy class implementing the Verticle interface or extending the AbstractVerticle
class.
Asynchronous Verticle Start and Stop
1. Sometimes we want to do some task in the start-up which takes some time and
you don’t want considered that verticle to be deployed until that happens.
2. There is an asynchronous start method, it takes Future as parameter. When
method return verticle will not be considered deployed.
3. When you finish your work then you have to call either complete or fail to signal
that you’re done.
Accessing Vert.x instance from verticle
You can access by using vertx variable/field.
◉ Access to Vert.x instance in Groovy Class
Verticle Types
◉ Standard Verticle
➢ They always executed using an event loop thread.
◉ Worker Verticle
➢ These run using a thread from worker pool. An instance is never executed
concurrent by more than one thread.
◉ Multi-Threaded Worker Verticle
➢ These run using a thread from the worker pool. An instance can be executed
concurrently by more than one thread.
Standard Verticles
◉ Standard Verticles are assigned and event loop thread when they are created and
the start method is called with that event loop.
◉ Vert.x will guarantee that all our code on Verticle instance is always executed on
the same event loop.
◉ Vert.x take care of:-
➢ Threading
➢ Scaling
➢ Synchronized
➢ Volatile
➢ Race Condition
➢ Deadlock
Worker Verticle
1. A worker verticle is just like Standard Verticle but it’s executed not using the an
event loop, but using a thread from the Vert.x worker thread pool.
2. It has been designed for calling blocking code, as they won’t block any event’s
loop.
3. You can also run inline blocking code directly while on an event loop.
4. It never executed concurrently by Vert.x by more than one thread, but can be by
different threads at different times.
5. To deploy Verticle as a worker you do that with setWorker.
Deploying Verticle programmatically
You can deploy a verticle using one of the method deployVerticle, specifying a verticle
name or you can pass in a verticle instance.
def myVerticle = new com.nexthoughts.MyVerticle()
vertx.deployVerticle(myVerticle)
You can also deploy by specifying verticle fully qualified name.
vertx.deployVerticle(‘com.nexthoughts.MyVerticle’)
The verticle name is used to look up specific VerticleFactory that will be used to
instantiate the actual verticle instances.
Rules for mapping a verticle name to a Verticle Factory
When deploying verticle using a name, the name is used to select the actual verticle
factory that will instantiate the verticle.
Verticle can have prefix which is a string followed by colon, which if present will be
used to look-up the factory.
js:foo.js //Use the JavaScript Verticle Factory.
groovy:com.nexthoughts.MyVerticle //Use the Groovy Verticle Factory
If no prefix present, Vert.x will look for a suffix and use that to lookup the factory.
Foo.js //Will also use the JavaScript verticle factory
MyVerticle.groovy //Will also use the Groovy verticle factory
If no prefix or suffix present then it by default Java fully qualified class name.
Most Verticles factories are loaded from the classpath and registered at Vert.x startup.
We can programmatically register and unregister verticles factories using
registerVerticleFactory and unregisterVerticleFactory respectively.
The Context Object
1. When Vert.x provides an event to a handler or calls the start and stop method of
Verticle, the execution is associated with a Context.
2. A context is an event-loop context and is tied to a specific event loop thread.
3. To retrieve the context use the getOrCreateContext method.
Executing periodic and delayed actions
It’s very common in Vert.x to want to perform an action after a delay, or periodically.
One-shot Timers
1. A one shot timer calls an event handler after a certain delay, expressed in
milliseconds.
2. To set a timer to fire once you use setTimer method passing in the delay and a
handler.
Periodic Timers
You can also set a timer to fire periodically by using setPeriodic()
Cancelling Timers
vertx.cancelTime(timerId)
Vert.x Services
i. Handling files
ii. Http Server
iii. JDBC Connector
iv. Mongo Client
v. SMTP Mail
vi. REST APIs
File Handling
1. The Vert.x FileSystem object provides many operations for manipulating the file
system.
2. There is one file system instance object per Vert.x instance, fileSystem.
3. Blocking and Non-Blocking version of each operations is provided. Non-blocking
version takes a handler which is called when operations completes or fails.
4. Vert.x provides an asynchronous file abstraction that allows you to manipulate a
file on the file system.
5. AsyncFile implements ReadStream and WriteStream so you can pump files to and
from other stream objects such as net sockets, http requests and responses and
WebSockets.
Code for Simple File Handling
def fs = vertx.fileSystem()
fs.copy("$path/foo.txt", "$path/bar.txt", { res ->
if (res.succeeded()) {
println("File has been copied")
} else {
println("Failed to Copy")
}
})
HTTP Server (Vert.x Web)
1. Vert.x Web is a great fit for writing RESTful HTTP micro-services.
2. Key Features:- Routing, Regular expression pattern matching for paths, Extraction
of parameter from path, Content Negotiation, Request Body Handling, Body Size
Limits, Cookie parsing, Multipart Form, Session, Error Page Handler, Basic
Authentication, Redirect based Authentication, User/Role/Permission
authorisation, Favicon handling, Templates (Thymeleaf, Response Time Handler)
3. compile 'io.vertx:vertx-web:3.5.0'
4. A Router is one of the core concept of Ver.x Web. It can maintain 0 to n Routes.
5. A router take HTTP request and finds the first matching route for that request, and
passes the request to that route.
6. When Vert.x Web decides to route a request to a matching route, it calls the
handler of the route passing in an instance of RoutingContext.
7. If you don’t end the response in your handler, you should call next so another
matching route can handle the request.
8. Handling
a. Routing by exact path
b. Routing with path that begins with something
c. Capturing Path parameter
d. Routing with Regular Expression.
e. Capturing path parameter with regular expression
f. Routing by HTTP Method
For more info
Code for simple http server
def server = vertx.createHttpServer()
server.requestHandler({ request ->
// This handler gets called for each request that arrives on the server
def response = request.response()
response.putHeader("content-type", "text/plain")
// Write to the response and end it
response.end("Hello World!")
})
server.listen(8080)
Vert.x JDBC Client
1. The client API is represented with the interface JDBCClient.
2. compile 'io.vertx:vertx-jdbc-client:3.5.0'
3. Creating the Client
a. Using default shared data source
b. Specifying a data source name
c. Creating a client with a non shared data source
d. Specifying a data source.
For more info
JDBC Demo
def client = JDBCClient.createShared(vertx, config, "MyDataSource")
client.getConnection({ res ->
if (res.succeeded()) {
def connection = res.result()
connection.query("SELECT * FROM some_table", { res2 ->
if (res2.succeeded()) {
def rs = res2.result()
// Do something with results
}
})
} else {
// Failed to get connection - deal with it
}
})
Vert.x Mail Client
1. Vert.x client for sending SMTP emails via a local mail server or by external
mail server.
2. compile 'io.vertx:vertx-mail-client:3.5.0'
3. Mail can be sent by creating a client that opens SMTP connections from Local JVM
For more info
Mail Client Demo
def config = [:]
def mailClient = MailClient.createShared(vertx, config, "exampleclient")
def message = [:]
message.from = "user@example.com (Example User)"
message.to = "recipient@example.org"
message.cc = "Another User <another@example.net>"
message.text = "this is the plain message text"
message.html = "this is html text <a href="http://vertx.io">vertx.io</a>"
mailClient.sendMail(message, { result ->
if (result.succeeded()) {
println(result.result())
} else {
result.cause().printStackTrace()
}
})
Service Discovery
1. In order to communicate with another peer, a microservice needs to know its
address.
2. We hard coded the addresses (eventbus address, URLs, location details) etc, but
this solution does not enable mobility.
3. Location transparency can be addressed by a pattern called service discovery.
4. Each microservice should announce (how to be invoked, characteristics, location,
metadata, securities and policies), this announcement are stored in service
discovery infrastructure known as service registry.
5. Two types of patterns can be used to consume services.
a. Client Side Server Discovery
b. Server Side Server Discovery
Vert.x Service Discovery
1. Vert.x provides an extensible service discovery mechanism, we can use client-side
or server-side service discovery using the same API.
2. It uses a distributed data structure shared on the Vert.x cluster.
Vertx in action
References
1. Guide for Java Devs
2. Groovy Doc
3. Node.js vs Vert.x
4. Vert.x Simple Tutorial
5. Vert.x Implementation
6. Vert.x Study Materials

More Related Content

What's hot

Monitoring using Prometheus and Grafana
Monitoring using Prometheus and GrafanaMonitoring using Prometheus and Grafana
Monitoring using Prometheus and GrafanaArvind Kumar G.S
 
Kubernetes for Beginners: An Introductory Guide
Kubernetes for Beginners: An Introductory GuideKubernetes for Beginners: An Introductory Guide
Kubernetes for Beginners: An Introductory GuideBytemark
 
Spring Cloud: Why? How? What?
Spring Cloud: Why? How? What?Spring Cloud: Why? How? What?
Spring Cloud: Why? How? What?Orkhan Gasimov
 
Docker introduction
Docker introductionDocker introduction
Docker introductiondotCloud
 
Introduction to Spring Cloud
Introduction to Spring Cloud           Introduction to Spring Cloud
Introduction to Spring Cloud VMware Tanzu
 
Introduction to kubernetes
Introduction to kubernetesIntroduction to kubernetes
Introduction to kubernetesRishabh Indoria
 
Kubernetes Introduction
Kubernetes IntroductionKubernetes Introduction
Kubernetes IntroductionPeng Xiao
 
Terraform modules and (some of) best practices
Terraform modules and (some of) best practicesTerraform modules and (some of) best practices
Terraform modules and (some of) best practicesAnton Babenko
 
Reactive programming
Reactive programmingReactive programming
Reactive programmingSUDIP GHOSH
 
쿠버네티스 ( Kubernetes ) 소개 자료
쿠버네티스 ( Kubernetes ) 소개 자료쿠버네티스 ( Kubernetes ) 소개 자료
쿠버네티스 ( Kubernetes ) 소개 자료Opennaru, inc.
 
Discover Quarkus and GraalVM
Discover Quarkus and GraalVMDiscover Quarkus and GraalVM
Discover Quarkus and GraalVMRomain Schlick
 
Log aggregation: using Elasticsearch, Fluentd/Fluentbit and Kibana (EFK)
Log aggregation: using Elasticsearch, Fluentd/Fluentbit and Kibana (EFK)Log aggregation: using Elasticsearch, Fluentd/Fluentbit and Kibana (EFK)
Log aggregation: using Elasticsearch, Fluentd/Fluentbit and Kibana (EFK)Lee Myring
 
Spring Native and Spring AOT
Spring Native and Spring AOTSpring Native and Spring AOT
Spring Native and Spring AOTVMware Tanzu
 
Kubernetes Introduction
Kubernetes IntroductionKubernetes Introduction
Kubernetes IntroductionEric Gustafson
 

What's hot (20)

Spring Boot
Spring BootSpring Boot
Spring Boot
 
Monitoring using Prometheus and Grafana
Monitoring using Prometheus and GrafanaMonitoring using Prometheus and Grafana
Monitoring using Prometheus and Grafana
 
GraalVM
GraalVMGraalVM
GraalVM
 
kubernetes, pourquoi et comment
kubernetes, pourquoi et commentkubernetes, pourquoi et comment
kubernetes, pourquoi et comment
 
Kubernetes for Beginners: An Introductory Guide
Kubernetes for Beginners: An Introductory GuideKubernetes for Beginners: An Introductory Guide
Kubernetes for Beginners: An Introductory Guide
 
Spring Cloud: Why? How? What?
Spring Cloud: Why? How? What?Spring Cloud: Why? How? What?
Spring Cloud: Why? How? What?
 
Docker introduction
Docker introductionDocker introduction
Docker introduction
 
Introduction to Spring Cloud
Introduction to Spring Cloud           Introduction to Spring Cloud
Introduction to Spring Cloud
 
Introduction to kubernetes
Introduction to kubernetesIntroduction to kubernetes
Introduction to kubernetes
 
Kubernetes Introduction
Kubernetes IntroductionKubernetes Introduction
Kubernetes Introduction
 
Terraform modules and (some of) best practices
Terraform modules and (some of) best practicesTerraform modules and (some of) best practices
Terraform modules and (some of) best practices
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
 
쿠버네티스 ( Kubernetes ) 소개 자료
쿠버네티스 ( Kubernetes ) 소개 자료쿠버네티스 ( Kubernetes ) 소개 자료
쿠버네티스 ( Kubernetes ) 소개 자료
 
Discover Quarkus and GraalVM
Discover Quarkus and GraalVMDiscover Quarkus and GraalVM
Discover Quarkus and GraalVM
 
Docker swarm
Docker swarmDocker swarm
Docker swarm
 
Log aggregation: using Elasticsearch, Fluentd/Fluentbit and Kibana (EFK)
Log aggregation: using Elasticsearch, Fluentd/Fluentbit and Kibana (EFK)Log aggregation: using Elasticsearch, Fluentd/Fluentbit and Kibana (EFK)
Log aggregation: using Elasticsearch, Fluentd/Fluentbit and Kibana (EFK)
 
Spring Native and Spring AOT
Spring Native and Spring AOTSpring Native and Spring AOT
Spring Native and Spring AOT
 
Kubernetes Introduction
Kubernetes IntroductionKubernetes Introduction
Kubernetes Introduction
 
02 api gateway
02 api gateway02 api gateway
02 api gateway
 

Viewers also liked (20)

JFree chart
JFree chartJFree chart
JFree chart
 
Apache tika
Apache tikaApache tika
Apache tika
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Cosmos DB Service
Cosmos DB ServiceCosmos DB Service
Cosmos DB Service
 
Progressive Web-App (PWA)
Progressive Web-App (PWA)Progressive Web-App (PWA)
Progressive Web-App (PWA)
 
Introduction to thymeleaf
Introduction to thymeleafIntroduction to thymeleaf
Introduction to thymeleaf
 
Jmh
JmhJmh
Jmh
 
Spring Web Flow
Spring Web FlowSpring Web Flow
Spring Web Flow
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
 
Introduction to gradle
Introduction to gradleIntroduction to gradle
Introduction to gradle
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
Hamcrest
HamcrestHamcrest
Hamcrest
 
Introduction to es6
Introduction to es6Introduction to es6
Introduction to es6
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
Jsoup
JsoupJsoup
Jsoup
 
Grails with swagger
Grails with swaggerGrails with swagger
Grails with swagger
 
HPC DAY 2017 | HPE Strategy And Portfolio for AI, BigData and HPC
HPC DAY 2017 | HPE Strategy And Portfolio for AI, BigData and HPCHPC DAY 2017 | HPE Strategy And Portfolio for AI, BigData and HPC
HPC DAY 2017 | HPE Strategy And Portfolio for AI, BigData and HPC
 
HPC DAY 2017 | Prometheus - energy efficient supercomputing
HPC DAY 2017 | Prometheus - energy efficient supercomputingHPC DAY 2017 | Prometheus - energy efficient supercomputing
HPC DAY 2017 | Prometheus - energy efficient supercomputing
 
Raspberry home server
Raspberry home serverRaspberry home server
Raspberry home server
 

Similar to Vertx

Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices ArchitectureIdan Fridman
 
BASICS OF VERT.X - A toolkit for building asynchronous and reactive app
BASICS OF VERT.X - A toolkit for building asynchronous and reactive appBASICS OF VERT.X - A toolkit for building asynchronous and reactive app
BASICS OF VERT.X - A toolkit for building asynchronous and reactive appHanaStevanovic
 
Vert.x Event Driven Non Blocking Reactive Toolkit
Vert.x Event Driven Non Blocking Reactive ToolkitVert.x Event Driven Non Blocking Reactive Toolkit
Vert.x Event Driven Non Blocking Reactive ToolkitBrian S. Paskin
 
Is OSGi modularity always worth it?
Is OSGi modularity always worth it?Is OSGi modularity always worth it?
Is OSGi modularity always worth it?glynnormington
 
SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8Ben Abdallah Helmi
 
Adv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfAdv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfKALAISELVI P
 
Kubernetes 101 VMworld 2019 workshop slides
Kubernetes 101 VMworld 2019 workshop slidesKubernetes 101 VMworld 2019 workshop slides
Kubernetes 101 VMworld 2019 workshop slidesSimone Morellato
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontrackingvamsi krishna
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarGal Marder
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
Devfest 2023 - Service Weaver Introduction - Taipei.pdf
Devfest 2023 - Service Weaver Introduction - Taipei.pdfDevfest 2023 - Service Weaver Introduction - Taipei.pdf
Devfest 2023 - Service Weaver Introduction - Taipei.pdfKAI CHU CHUNG
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .happycocoman
 
Multi threading
Multi threadingMulti threading
Multi threadinggndu
 
VerneMQ @ Paris Erlang User Group June 29th 2015
VerneMQ @ Paris Erlang User Group June 29th 2015VerneMQ @ Paris Erlang User Group June 29th 2015
VerneMQ @ Paris Erlang User Group June 29th 2015André Graf
 
Verne mq @ paris erlang user group
Verne mq @ paris erlang user groupVerne mq @ paris erlang user group
Verne mq @ paris erlang user grouperlangparis
 

Similar to Vertx (20)

Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices Architecture
 
BASICS OF VERT.X - A toolkit for building asynchronous and reactive app
BASICS OF VERT.X - A toolkit for building asynchronous and reactive appBASICS OF VERT.X - A toolkit for building asynchronous and reactive app
BASICS OF VERT.X - A toolkit for building asynchronous and reactive app
 
Vert.x Event Driven Non Blocking Reactive Toolkit
Vert.x Event Driven Non Blocking Reactive ToolkitVert.x Event Driven Non Blocking Reactive Toolkit
Vert.x Event Driven Non Blocking Reactive Toolkit
 
The Veil-Framework
The Veil-FrameworkThe Veil-Framework
The Veil-Framework
 
Vertx Basics
Vertx BasicsVertx Basics
Vertx Basics
 
Is OSGi modularity always worth it?
Is OSGi modularity always worth it?Is OSGi modularity always worth it?
Is OSGi modularity always worth it?
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Getting groovier-with-vertx
Getting groovier-with-vertxGetting groovier-with-vertx
Getting groovier-with-vertx
 
SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8
 
Adv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfAdv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdf
 
Kubernetes 101 VMworld 2019 workshop slides
Kubernetes 101 VMworld 2019 workshop slidesKubernetes 101 VMworld 2019 workshop slides
Kubernetes 101 VMworld 2019 workshop slides
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and Quasar
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Devfest 2023 - Service Weaver Introduction - Taipei.pdf
Devfest 2023 - Service Weaver Introduction - Taipei.pdfDevfest 2023 - Service Weaver Introduction - Taipei.pdf
Devfest 2023 - Service Weaver Introduction - Taipei.pdf
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .
 
Multi threading
Multi threadingMulti threading
Multi threading
 
VerneMQ @ Paris Erlang User Group June 29th 2015
VerneMQ @ Paris Erlang User Group June 29th 2015VerneMQ @ Paris Erlang User Group June 29th 2015
VerneMQ @ Paris Erlang User Group June 29th 2015
 
Verne mq @ paris erlang user group
Verne mq @ paris erlang user groupVerne mq @ paris erlang user group
Verne mq @ paris erlang user group
 

More from NexThoughts Technologies (20)

Alexa skill
Alexa skillAlexa skill
Alexa skill
 
Docker & kubernetes
Docker & kubernetesDocker & kubernetes
Docker & kubernetes
 
Apache commons
Apache commonsApache commons
Apache commons
 
HazelCast
HazelCastHazelCast
HazelCast
 
MySQL Pro
MySQL ProMySQL Pro
MySQL Pro
 
Microservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & ReduxMicroservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & Redux
 
Swagger
SwaggerSwagger
Swagger
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Arango DB
Arango DBArango DB
Arango DB
 
Jython
JythonJython
Jython
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Smart Contract samples
Smart Contract samplesSmart Contract samples
Smart Contract samples
 
My Doc of geth
My Doc of gethMy Doc of geth
My Doc of geth
 
Geth important commands
Geth important commandsGeth important commands
Geth important commands
 
Ethereum genesis
Ethereum genesisEthereum genesis
Ethereum genesis
 
Ethereum
EthereumEthereum
Ethereum
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Google authentication
Google authenticationGoogle authentication
Google authentication
 
Java 9 Features
Java 9 FeaturesJava 9 Features
Java 9 Features
 
Postgresql
PostgresqlPostgresql
Postgresql
 

Recently uploaded

Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

Vertx

  • 1. Introducing Vertx By: Vijay Shukla & Vishal Sahu
  • 2. Agenda 1. Introduction 2. Main Component 3. Threading and Programming Model 4. Installation 5. Event Bus 6. Verticle 7. Services 8. Templates
  • 3. Introduction ● Vert.x is a toolkit or platform for implementing reactive applications on the JVM. ● Vert.x is an open-source project at the Eclipse Foundation. Vert.x was initiated in 2012 by Tim Fox. ● General Purpose Application Framework ● Polyglot (Java, Groovy, Scala, Kotlin, JavaScript, Ruby and Ceylon) ● Event Driven, non-blocking ● Lightweight & fast ● Reusable modules.
  • 5. Main Components 1. Verticles - the building blocks 2. Event Bus & Event Loop 3. Future 4. Routes
  • 6. Threading and Programming Model 1. The synchronous I/O threading model are simple to understand, but it hurts scalability with too many concurrent connections. 2. Operating System spends significant time just on thread scheduling management. 3. The unit of deployment in Vert.x is called a Verticle. A verticle processes incoming events over an event-loop. 4. Event-loops are typical in asynchronous programming models. 5. Every loop is attached to a thread. By default Vert.x attaches 2 event loops per CPU core thread. 6. The direct consequence is that a regular verticle always processes events on the same thread, so there is no need to use thread coordination mechanisms to manipulate a verticle state
  • 7. 7. Verticles run in single thread mode. 8. A verticle is only ever executed by a single thread, and always by the same thread. 9. It is capable of using all the CPUs in machine, or cores in CPU. 10. It does this by creating one thread per CPU. 11. Each thread can send message to multiple verticles. 12. Verticles are event driven and are only running when receiving message, so a verticles does not need to have its own exclusive thread.
  • 8. Comparison of Performance When Only 200/OK Response Has Been Returned.
  • 9. Comparison of Performance When a 72-byte Static HTML File is Returned.
  • 11.
  • 12.
  • 13.
  • 15. Vertx Command Line The vertx command is used to interact with Vert.x from the command line. Download and set PATH environment variable. (Make sure Java 8 installed and used) vertx run my-verticle.groovy OR vertx run groovy:com.nexthoughts.MyGroovyVerticle
  • 17. Create Vertx Instance You can create a Vertx instance by calling Vertx.vertx(). 1. The Vertx instance creates a number of threads internally to handle the exchange of messages between verticles. 2. These threads are not daemon threads, so they prevent the JVM from shutting down, event of the main thread creating the Vertx instance terminates. 3. When creating the Vertx Object you can also provide options if the default is not right for you. 4. The VertxOptions object has many settings and allows you to configure things like clustering, high availability, pool sizes etc.
  • 18. Event Bus - Introduction 1. Verticles are event driven, meaning they do not run unless they receive a message. 2. Verticles can communicate with each other via the Vert.x event Bus.
  • 19. 3. Message can be simple objects (e.g. Java Objects), Strings, CSV, JSON, binary data or whatever else you need. 4. Verticles can send and listen to addresses. 5. An address is like a named channel. 6. When a message is sent to a given address, all verticles that listen on that address receive the message. 7. Verticles can subscribe and unsubscribe to address without the ender knowing. 8. This results in a very loose coupling between message senders and message receivers.
  • 20.
  • 21. Using The Event Bus Is is very common for verticles to either listen for incoming messages from the event bus, or to write messages to other verticles via the event bus. Listening for Message 1. When a verticle wants to listen for message from the bus, it listen on certain address. An address is just a name. 2. Multiple verticles can listen for messages on the same address and multiple verticles can send messages to an address. 3. A verticle can obtain a reference to the event bus via the vertx instance inherited from AbstractVerticle
  • 22. Registering Handlers 1. When a message arrives for your handler, you handler will be called, passing in the message. 2. The object returned from call to consumer() is an instance of MessageConsumer. 3. When registering a handler on a clustered event bus, it can take some time for the registration to reach all nodes of the cluster. You can register/unregister a completion handler to be notified.
  • 23. Publishing/Sending Message eventBus.publish(“address”,”Send Some message here”) eventBus.send(“address”,”Send Some message here”) Sending a message will result in only one handler registered at the address receiving the message. You can also send message on event bus with headers. def options=[headers:[“some-header-key”:”some-header-value”]] vertx.eventBus().send(“address”,”Some Message to be sent”,options) To acknowledge that the message has been processed the consumer can reply to the message by calling reply.
  • 24. Verticles 1. Introduction 2. Create Verticle 3. Start and Stop Verticle Asynchronous 4. Accessing Vert.x instance from Verticle 5. Vert.x type a. Standard b. Worker c. Multi-Threaded 6. Deployment Verticle Programmatically 7. Rules for mapping verticle instance to Verticle Factory.
  • 25. Introduction Vert.x can deploy and execute components called Verticles.
  • 26. A Verticle can be passed some configuration (e.g, credentials, network addresses, etc).
  • 27. 1. Incoming network data can be received from accepting threads then passed as events to corresponding Verticles. 2. If the Verticle deployed more than once, then the events are being distributed to verticles instances in a round-robin fashion.
  • 28. 1. The Vertx instance by itself doesn’t do much except all thread management, creating an event bus etc. 2. In order to get the application to do something useful, you need to deploy one or more verticles (component) inside the Vertx instance. 3. Before you can deploy a verticles you need to create it. 4. You can create a verticle by extending a class AbstractVerticle. 5. A verticle has a start() and a stop() method which are called when the verticles is deployed and undeployed respectively. 6. Perform any necessary initialization work inside the start() and necessary cleanup in stop(). Create Verticle
  • 29. An application would typically be composed of many verticle instances running in the same Vert.x instance at same time. The different Verticle Instance communicate with each other by sending message on the event bus. Two alternatives to create verticles: 1. A plain groovy script 2. A groovy class implementing the Verticle interface or extending the AbstractVerticle class.
  • 30. Asynchronous Verticle Start and Stop 1. Sometimes we want to do some task in the start-up which takes some time and you don’t want considered that verticle to be deployed until that happens. 2. There is an asynchronous start method, it takes Future as parameter. When method return verticle will not be considered deployed. 3. When you finish your work then you have to call either complete or fail to signal that you’re done.
  • 31. Accessing Vert.x instance from verticle You can access by using vertx variable/field. ◉ Access to Vert.x instance in Groovy Class Verticle Types ◉ Standard Verticle ➢ They always executed using an event loop thread. ◉ Worker Verticle ➢ These run using a thread from worker pool. An instance is never executed concurrent by more than one thread. ◉ Multi-Threaded Worker Verticle ➢ These run using a thread from the worker pool. An instance can be executed concurrently by more than one thread.
  • 32. Standard Verticles ◉ Standard Verticles are assigned and event loop thread when they are created and the start method is called with that event loop. ◉ Vert.x will guarantee that all our code on Verticle instance is always executed on the same event loop. ◉ Vert.x take care of:- ➢ Threading ➢ Scaling ➢ Synchronized ➢ Volatile ➢ Race Condition ➢ Deadlock
  • 33. Worker Verticle 1. A worker verticle is just like Standard Verticle but it’s executed not using the an event loop, but using a thread from the Vert.x worker thread pool. 2. It has been designed for calling blocking code, as they won’t block any event’s loop. 3. You can also run inline blocking code directly while on an event loop. 4. It never executed concurrently by Vert.x by more than one thread, but can be by different threads at different times. 5. To deploy Verticle as a worker you do that with setWorker.
  • 34. Deploying Verticle programmatically You can deploy a verticle using one of the method deployVerticle, specifying a verticle name or you can pass in a verticle instance. def myVerticle = new com.nexthoughts.MyVerticle() vertx.deployVerticle(myVerticle) You can also deploy by specifying verticle fully qualified name. vertx.deployVerticle(‘com.nexthoughts.MyVerticle’) The verticle name is used to look up specific VerticleFactory that will be used to instantiate the actual verticle instances.
  • 35. Rules for mapping a verticle name to a Verticle Factory When deploying verticle using a name, the name is used to select the actual verticle factory that will instantiate the verticle. Verticle can have prefix which is a string followed by colon, which if present will be used to look-up the factory. js:foo.js //Use the JavaScript Verticle Factory. groovy:com.nexthoughts.MyVerticle //Use the Groovy Verticle Factory
  • 36. If no prefix present, Vert.x will look for a suffix and use that to lookup the factory. Foo.js //Will also use the JavaScript verticle factory MyVerticle.groovy //Will also use the Groovy verticle factory If no prefix or suffix present then it by default Java fully qualified class name. Most Verticles factories are loaded from the classpath and registered at Vert.x startup. We can programmatically register and unregister verticles factories using registerVerticleFactory and unregisterVerticleFactory respectively.
  • 37. The Context Object 1. When Vert.x provides an event to a handler or calls the start and stop method of Verticle, the execution is associated with a Context. 2. A context is an event-loop context and is tied to a specific event loop thread. 3. To retrieve the context use the getOrCreateContext method.
  • 38. Executing periodic and delayed actions It’s very common in Vert.x to want to perform an action after a delay, or periodically. One-shot Timers 1. A one shot timer calls an event handler after a certain delay, expressed in milliseconds. 2. To set a timer to fire once you use setTimer method passing in the delay and a handler. Periodic Timers You can also set a timer to fire periodically by using setPeriodic() Cancelling Timers vertx.cancelTime(timerId)
  • 39. Vert.x Services i. Handling files ii. Http Server iii. JDBC Connector iv. Mongo Client v. SMTP Mail vi. REST APIs
  • 40. File Handling 1. The Vert.x FileSystem object provides many operations for manipulating the file system. 2. There is one file system instance object per Vert.x instance, fileSystem. 3. Blocking and Non-Blocking version of each operations is provided. Non-blocking version takes a handler which is called when operations completes or fails. 4. Vert.x provides an asynchronous file abstraction that allows you to manipulate a file on the file system. 5. AsyncFile implements ReadStream and WriteStream so you can pump files to and from other stream objects such as net sockets, http requests and responses and WebSockets.
  • 41. Code for Simple File Handling def fs = vertx.fileSystem() fs.copy("$path/foo.txt", "$path/bar.txt", { res -> if (res.succeeded()) { println("File has been copied") } else { println("Failed to Copy") } })
  • 42. HTTP Server (Vert.x Web) 1. Vert.x Web is a great fit for writing RESTful HTTP micro-services. 2. Key Features:- Routing, Regular expression pattern matching for paths, Extraction of parameter from path, Content Negotiation, Request Body Handling, Body Size Limits, Cookie parsing, Multipart Form, Session, Error Page Handler, Basic Authentication, Redirect based Authentication, User/Role/Permission authorisation, Favicon handling, Templates (Thymeleaf, Response Time Handler) 3. compile 'io.vertx:vertx-web:3.5.0' 4. A Router is one of the core concept of Ver.x Web. It can maintain 0 to n Routes. 5. A router take HTTP request and finds the first matching route for that request, and passes the request to that route. 6. When Vert.x Web decides to route a request to a matching route, it calls the handler of the route passing in an instance of RoutingContext.
  • 43. 7. If you don’t end the response in your handler, you should call next so another matching route can handle the request. 8. Handling a. Routing by exact path b. Routing with path that begins with something c. Capturing Path parameter d. Routing with Regular Expression. e. Capturing path parameter with regular expression f. Routing by HTTP Method For more info
  • 44. Code for simple http server def server = vertx.createHttpServer() server.requestHandler({ request -> // This handler gets called for each request that arrives on the server def response = request.response() response.putHeader("content-type", "text/plain") // Write to the response and end it response.end("Hello World!") }) server.listen(8080)
  • 45. Vert.x JDBC Client 1. The client API is represented with the interface JDBCClient. 2. compile 'io.vertx:vertx-jdbc-client:3.5.0' 3. Creating the Client a. Using default shared data source b. Specifying a data source name c. Creating a client with a non shared data source d. Specifying a data source. For more info
  • 46. JDBC Demo def client = JDBCClient.createShared(vertx, config, "MyDataSource") client.getConnection({ res -> if (res.succeeded()) { def connection = res.result() connection.query("SELECT * FROM some_table", { res2 -> if (res2.succeeded()) { def rs = res2.result() // Do something with results } }) } else { // Failed to get connection - deal with it } })
  • 47. Vert.x Mail Client 1. Vert.x client for sending SMTP emails via a local mail server or by external mail server. 2. compile 'io.vertx:vertx-mail-client:3.5.0' 3. Mail can be sent by creating a client that opens SMTP connections from Local JVM For more info
  • 48. Mail Client Demo def config = [:] def mailClient = MailClient.createShared(vertx, config, "exampleclient") def message = [:] message.from = "user@example.com (Example User)" message.to = "recipient@example.org" message.cc = "Another User <another@example.net>" message.text = "this is the plain message text" message.html = "this is html text <a href="http://vertx.io">vertx.io</a>" mailClient.sendMail(message, { result -> if (result.succeeded()) { println(result.result()) } else { result.cause().printStackTrace() } })
  • 49. Service Discovery 1. In order to communicate with another peer, a microservice needs to know its address. 2. We hard coded the addresses (eventbus address, URLs, location details) etc, but this solution does not enable mobility. 3. Location transparency can be addressed by a pattern called service discovery. 4. Each microservice should announce (how to be invoked, characteristics, location, metadata, securities and policies), this announcement are stored in service discovery infrastructure known as service registry. 5. Two types of patterns can be used to consume services. a. Client Side Server Discovery b. Server Side Server Discovery
  • 50.
  • 51.
  • 52. Vert.x Service Discovery 1. Vert.x provides an extensible service discovery mechanism, we can use client-side or server-side service discovery using the same API. 2. It uses a distributed data structure shared on the Vert.x cluster.
  • 53.
  • 55.
  • 56.
  • 57. References 1. Guide for Java Devs 2. Groovy Doc 3. Node.js vs Vert.x 4. Vert.x Simple Tutorial 5. Vert.x Implementation 6. Vert.x Study Materials