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

The aggregate is dead! Long live the aggregate! - SpringIO.pdf
The aggregate is dead! Long live the aggregate! - SpringIO.pdfThe aggregate is dead! Long live the aggregate! - SpringIO.pdf
The aggregate is dead! Long live the aggregate! - SpringIO.pdf
Sara Pellegrini
 
Quarkus - a next-generation Kubernetes Native Java framework
Quarkus - a next-generation Kubernetes Native Java frameworkQuarkus - a next-generation Kubernetes Native Java framework
Quarkus - a next-generation Kubernetes Native Java framework
SVDevOps
 

What's hot (20)

Citrix Day 2014: XenApp / XenDesktop 7.6
Citrix Day 2014: XenApp / XenDesktop 7.6Citrix Day 2014: XenApp / XenDesktop 7.6
Citrix Day 2014: XenApp / XenDesktop 7.6
 
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
Developing event-driven microservices with event sourcing and CQRS  (svcc, sv...Developing event-driven microservices with event sourcing and CQRS  (svcc, sv...
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
 
Struts Interceptors
Struts InterceptorsStruts Interceptors
Struts Interceptors
 
Resilience4j with Spring Boot
Resilience4j with Spring BootResilience4j with Spring Boot
Resilience4j with Spring Boot
 
WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4
 
J2ee
J2eeJ2ee
J2ee
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and Karma
 
Active Object Design Pattern
Active Object Design PatternActive Object Design Pattern
Active Object Design Pattern
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
炎炎夏日學 Android 課程 - Part1: Kotlin 語法介紹
炎炎夏日學 Android 課程 -  Part1: Kotlin 語法介紹炎炎夏日學 Android 課程 -  Part1: Kotlin 語法介紹
炎炎夏日學 Android 課程 - Part1: Kotlin 語法介紹
 
Design patterns for microservice architecture
Design patterns for microservice architectureDesign patterns for microservice architecture
Design patterns for microservice architecture
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
Kubernetes Disaster Recovery - Los Angeles K8s meetup Dec 10 2019
Kubernetes Disaster Recovery - Los Angeles K8s meetup Dec 10 2019Kubernetes Disaster Recovery - Los Angeles K8s meetup Dec 10 2019
Kubernetes Disaster Recovery - Los Angeles K8s meetup Dec 10 2019
 
The aggregate is dead! Long live the aggregate! - SpringIO.pdf
The aggregate is dead! Long live the aggregate! - SpringIO.pdfThe aggregate is dead! Long live the aggregate! - SpringIO.pdf
The aggregate is dead! Long live the aggregate! - SpringIO.pdf
 
Quarkus - a next-generation Kubernetes Native Java framework
Quarkus - a next-generation Kubernetes Native Java frameworkQuarkus - a next-generation Kubernetes Native Java framework
Quarkus - a next-generation Kubernetes Native Java framework
 
Shaping serverless architecture with domain driven design patterns
Shaping serverless architecture with domain driven design patternsShaping serverless architecture with domain driven design patterns
Shaping serverless architecture with domain driven design patterns
 
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트
 
Spring Caches with Protocol Buffers
Spring Caches with Protocol BuffersSpring Caches with Protocol Buffers
Spring Caches with Protocol Buffers
 
Looming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdfLooming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdf
 
Docker Kubernetes Istio
Docker Kubernetes IstioDocker Kubernetes Istio
Docker Kubernetes Istio
 

Viewers also liked

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

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
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
vamsi krishna
 

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

More from NexThoughts Technologies (20)

Alexa skill
Alexa skillAlexa skill
Alexa skill
 
GraalVM
GraalVMGraalVM
GraalVM
 
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
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Google authentication
Google authenticationGoogle authentication
Google authentication
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

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