SlideShare a Scribd company logo
1 of 52
Building Reactive Microservices with Vert.x
Claudio Eduardo de Oliveira
About me
Claudio Eduardo de Oliveira
Developer @ Daitan Group
Bacharel em Ciência da Computação
Cursando MBA em Arquitetura de Soluções em
Tecnologia (DeVry/Metrocamp)
Entusiasta Docker / Spring / Vert.x Contatos:
Email: claudioed.oliveira@gmail.com
Linkedin: https://br.linkedin.com/in/claudioedoliveira
Twitter: @claudioed
Agenda
● Microservices
○ Definition
○ Patterns
● Reactive Manifesto
○ Reactive Systems
○ Reactive Programming
● Vert.x
Definition
The term "Microservice Architecture" has sprung up over the last
few years to describe a particular way of designing software
applications as suites of independently deployable services.
While there is no precise definition of this architectural style,
there are certain common characteristics around organization
around business capability, automated deployment, intelligence in
the endpoints, and decentralized control of languages and data.
microservices
https://martinfowler.com/articles/microservices.html
Example microservices
https://cdn.wp.nginx.com/wp-content/uploads/2016/04/Richardson-microservices-part1-2_microservices-architecture.png
Microservices Patterns
● Circuit Breakers
● Service Discovery
microservices
Circuit Breaker microservices
“The basic idea behind the circuit breaker is very simple. You
wrap a protected function call in a circuit breaker object,
which monitors for failures”
https://martinfowler.com/bliki/CircuitBreaker.html
Service Discovery microservices
Service discovery is the automatic detection of devices and
services offered by these devices on a computer network
https://en.wikipedia.org/wiki/Service_discovery
reactiveReactive Manifesto
http://www.reactivemanifesto.org/
Reactive Systems
as defined by the Reactive Manifesto—is a set of
architectural design principles for building modern
systems that are well prepared to meet the
increasing demands that applications face today.
https://www.lightbend.com/reactive-programming-versus-reactive-systems
reactive
Reactive Programming
In computing, reactive programming is an
asynchronous programming paradigm
concerned with data streams and the
propagation of change
https://en.wikipedia.org/wiki/Reactive_programming
reactive
We will talk about Reactive Systems….
reactive
Some JVM players reactive
Definition
Eclipse Vert.x is a toolkit for building
reactive applications on the JVM
vert.x
http://vertx.io/
Highlights
● Non-Blocking (vert.x
core)
● Polyglot
● Event Bus
● General purpose
● Unopinionated
vert.x
NO Black Magic - Spring Way vert.x
@SpringBootApplication
@EnableHystrix
public class MusicRecommendationApplication {
public static void main(String[] args) {
SpringApplication
.run(MusicRecommendationApplication.class, args);
}
}
NO Black Magic vert.x
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
…….}
Vert.x Way vert.x
public class EventLoopVerticle extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(EventLoopVerticle.class);
public void start() {
final Router router = Router.router(vertx);
router.get("/test").handler(req -> {
LOGGER.info(" receiving request");
req.response()
.putHeader("content-type","text/plain")
.end(NormalProcess.process());
});
vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}
}
Dependencies - Maven vert.x
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-dependencies</artifactId>
<version>${vertx.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-core</artifactId>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
</dependency>
Core Concepts
Verticle
vert.x
Event Bus
Verticle vert.x
● Small Vert Unit
● Regular Verticle
● Worker Verticle
● Multi Threaded Worker
● Automatic node discovery
Reactor Pattern
The reactor pattern is one implementation technique of event-
driven architecture. In simple terms, it uses a single threaded
event loop blocking on resource-emitting events and
dispatches them to corresponding handlers and callbacks
vert.x
https://dzone.com/articles/understanding-reactor-pattern-thread-based-and-eve
Regular Verticle - Event Loop vert.x
Reactor Pattern - Vert.x vert.x
Demo vert.x
Regular Verticle
● Golden Rule - Don’t block me!
● Event Loop (more than one)
● Multi Reactor Pattern
● High throughput (i.e http)
vert.x
public class EventLoopVerticle extends AbstractVerticle {
public void start() {
final Router router = Router.router(vertx);
router.get("/test").handler(req -> {
req.response()
.putHeader("content-type","text/plain")
.end(NormalProcess.process());
});
vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}
}
Regular Verticle - Example vert.x
Don't do this !!!! vert.x
public class EventLoopBlockerVerticle extends AbstractVerticle {
public void start() {
final Router router = Router.router(vertx);
router.get("/test").handler(req -> {
LongRunningProcess.longProcess();
final String date = LocalDateTime.now().toString();
req.response()
.putHeader("content-type","text/plain")
.end(String.format("TDC 2017 %s", date));
});
vertx.createHttpServer().requestHandler(router::accept).listen(8081);
}
}
Worker Verticle
● Vert.x worker thread pool
● Execute blocking code
● They are never executed by more than one thread
● Background tasks
vert.x
Worker Verticle vert.x
public class EventLoopBusVerticle extends AbstractVerticle {
public void start() {
this.vertx.deployVerticle(new BusVerticle(),
new DeploymentOptions().setWorker(true));
this.vertx.deployVerticle(new RequestResourceVerticle());
}
}
Multi Threaded Verticle
● Based on worker verticle
● Can be executed concurrently by different threads
● Hard to code because you need to maintain states
between verticles
● Specific needs
vert.x
Event Bus
● Nervous system of Vert.x
● Publish / Subscribe
● Point to Point
● Request Response
● Can be distributed
vert.x
Event Bus vert.x
http://allegro.tech/2015/11/real-time-web-application-with-websockets-and-vert-x.html
Event Bus vert.x
public class RequestResourceVerticle extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(BusVerticle.class);
public void start() {
final EventBus eventBus = vertx.eventBus();
final Router router = Router.router(vertx);
router.get("/test").handler(req -> {
eventBus.send("data-stream", new JsonObject(), responseBus -> {
if (responseBus.succeeded()) {
req.response()
.putHeader("content-type", "text/plain")
.end(responseBus.result().body().toString());
}
});
});
vertx.createHttpServer().requestHandler(router::accept).listen(8082);
}
}
Service Discovery
This component provides an infrastructure to publish and
discover various resources, such as service proxies, HTTP
endpoints, data sources…​
vert.x
http://vertx.io/docs/vertx-service-discovery/java/
Service Discovery
Service provider
Publish / Unpublish service record
Update the status of a service
vert.x
http://vertx.io/docs/vertx-service-discovery/java/
Service Discovery
Service consumer
Lookup service
Bind to a selected service
Release the service
Listen for arrival and departure
vert.x
http://vertx.io/docs/vertx-service-discovery/java/
Service Discovery - Backend vert.x
final ServiceDiscoveryOptions serviceDiscoveryOptions = new ServiceDiscoveryOptions()
.setBackendConfiguration(
new JsonObject()
.put("host", "127.0.0.1")
.put("port", "6379")
);
ServiceDiscovery sd = ServiceDiscovery.create(vertx,serviceDiscoveryOptions);
Service Discovery - Publish vert.x
vertx.createHttpServer().requestHandler(router::accept)
.rxListen(8083)
.flatMap(httpServer -> discovery
.rxPublish(HttpEndpoint.createRecord("product", "localhost", 8083, "/")))
.subscribe(rec -> LOGGER.info("Product Service is published"));
Service Discovery - Consumer vert.x
final ServiceDiscoveryOptions serviceDiscoveryOptions = new ServiceDiscoveryOptions()
.setBackendConfiguration(
new JsonObject()
.put("host", "127.0.0.1")
.put("port", "6379")
);
ServiceDiscovery discovery = ServiceDiscovery.create(vertx,serviceDiscoveryOptions);
….
HttpEndpoint.rxGetWebClient(discovery, rec -> rec.getName().endsWith("product"))
.flatMap(client -> client.get("/product/" + id).as(BodyCodec.string()).rxSend())
.subscribe(response -> req.response()
.putHeader("content-type", "application/json")
.end(response.body()));
});
Service Discovery
● Consul
● Kubernetes
● Redis
● Docker
vert.x
Circuit Breaker vert.x
https://www.oreilly.com/ideas/microservices-antipatterns-and-pitfalls
breaker.executeWithFallback(
future -> {
vertx.createHttpClient().getNow(8080, "localhost", "/", response -> {
if (response.statusCode() != 200) {
future.fail("HTTP error");
} else {
response
.exceptionHandler(future::fail)
.bodyHandler(buffer -> {
future.complete(buffer.toString());
});
}
});
}, v -> {
// Executed when the circuit is opened
return "Hello";
})
.setHandler(ar -> {
// Do something with the result
});
Circuit Breaker vert.x
Relational Database Integrations
● MySQL
● PostgreSQL
● JDBC
vert.x
NoSQL Database Integrations
● Redis
● MongoDB
● Cassandra
● OrientDB
vert.x
Messaging
● Kafka
● MQTT
● ZeroMQ
● RabbitMQ
● AMQP 1.0
vert.x
vert.xDemo
Demo vert.x
References
http://vertx.io/docs/guide-for-java-devs/
https://www.oreilly.com/ideas/reactive-programming-vs-reactive-systems
https://dzone.com/articles/understanding-reactor-pattern-thread-based-and-eve
https://developers.redhat.com/promotions/building-reactive-microservices-in-java/
https://github.com/claudioed/travel-helper

More Related Content

Similar to Vertx daitan

softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EEAlexis Hassler
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Michel Schudel
 
Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)Woonsan Ko
 
2008 - TechDays PT: Building Software + Services with Volta
2008 - TechDays PT: Building Software + Services with Volta2008 - TechDays PT: Building Software + Services with Volta
2008 - TechDays PT: Building Software + Services with VoltaDaniel Fisher
 
Dropwizard Introduction
Dropwizard IntroductionDropwizard Introduction
Dropwizard IntroductionAnthony Chen
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym Khondar
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin componentsPeter Lehto
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2Hugo Hamon
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsAleksandar Ilić
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsPSTechSerbia
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android JetpackAhmad Arif Faizin
 
SeedStack feature tour
SeedStack feature tourSeedStack feature tour
SeedStack feature tourSeedStack
 

Similar to Vertx daitan (20)

Building Reactive Microservices with Vert.x
Building Reactive Microservices with Vert.xBuilding Reactive Microservices with Vert.x
Building Reactive Microservices with Vert.x
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
Arquitecturas de microservicios - Medianet Software
Arquitecturas de microservicios   -  Medianet SoftwareArquitecturas de microservicios   -  Medianet Software
Arquitecturas de microservicios - Medianet Software
 
Hexagonal architecture in PHP
Hexagonal architecture in PHPHexagonal architecture in PHP
Hexagonal architecture in PHP
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Android best practices
Android best practicesAndroid best practices
Android best practices
 
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
 
Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)
 
2008 - TechDays PT: Building Software + Services with Volta
2008 - TechDays PT: Building Software + Services with Volta2008 - TechDays PT: Building Software + Services with Volta
2008 - TechDays PT: Building Software + Services with Volta
 
Dropwizard Introduction
Dropwizard IntroductionDropwizard Introduction
Dropwizard Introduction
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin components
 
Clean Architecture @ Taxibeat
Clean Architecture @ TaxibeatClean Architecture @ Taxibeat
Clean Architecture @ Taxibeat
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
 
Android - Anatomy of android elements & layouts
Android - Anatomy of android elements & layoutsAndroid - Anatomy of android elements & layouts
Android - Anatomy of android elements & layouts
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android Jetpack
 
SeedStack feature tour
SeedStack feature tourSeedStack feature tour
SeedStack feature tour
 

Recently uploaded

What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 

Recently uploaded (20)

What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 

Vertx daitan

  • 1. Building Reactive Microservices with Vert.x Claudio Eduardo de Oliveira
  • 2. About me Claudio Eduardo de Oliveira Developer @ Daitan Group Bacharel em Ciência da Computação Cursando MBA em Arquitetura de Soluções em Tecnologia (DeVry/Metrocamp) Entusiasta Docker / Spring / Vert.x Contatos: Email: claudioed.oliveira@gmail.com Linkedin: https://br.linkedin.com/in/claudioedoliveira Twitter: @claudioed
  • 3. Agenda ● Microservices ○ Definition ○ Patterns ● Reactive Manifesto ○ Reactive Systems ○ Reactive Programming ● Vert.x
  • 4. Definition The term "Microservice Architecture" has sprung up over the last few years to describe a particular way of designing software applications as suites of independently deployable services. While there is no precise definition of this architectural style, there are certain common characteristics around organization around business capability, automated deployment, intelligence in the endpoints, and decentralized control of languages and data. microservices https://martinfowler.com/articles/microservices.html
  • 6. Microservices Patterns ● Circuit Breakers ● Service Discovery microservices
  • 7. Circuit Breaker microservices “The basic idea behind the circuit breaker is very simple. You wrap a protected function call in a circuit breaker object, which monitors for failures” https://martinfowler.com/bliki/CircuitBreaker.html
  • 8. Service Discovery microservices Service discovery is the automatic detection of devices and services offered by these devices on a computer network https://en.wikipedia.org/wiki/Service_discovery
  • 10. Reactive Systems as defined by the Reactive Manifesto—is a set of architectural design principles for building modern systems that are well prepared to meet the increasing demands that applications face today. https://www.lightbend.com/reactive-programming-versus-reactive-systems reactive
  • 11. Reactive Programming In computing, reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change https://en.wikipedia.org/wiki/Reactive_programming reactive
  • 12. We will talk about Reactive Systems…. reactive
  • 13. Some JVM players reactive
  • 14.
  • 15.
  • 16. Definition Eclipse Vert.x is a toolkit for building reactive applications on the JVM vert.x http://vertx.io/
  • 17. Highlights ● Non-Blocking (vert.x core) ● Polyglot ● Event Bus ● General purpose ● Unopinionated vert.x
  • 18. NO Black Magic - Spring Way vert.x @SpringBootApplication @EnableHystrix public class MusicRecommendationApplication { public static void main(String[] args) { SpringApplication .run(MusicRecommendationApplication.class, args); } }
  • 19. NO Black Magic vert.x @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication { …….}
  • 20. Vert.x Way vert.x public class EventLoopVerticle extends AbstractVerticle { private static final Logger LOGGER = LoggerFactory.getLogger(EventLoopVerticle.class); public void start() { final Router router = Router.router(vertx); router.get("/test").handler(req -> { LOGGER.info(" receiving request"); req.response() .putHeader("content-type","text/plain") .end(NormalProcess.process()); }); vertx.createHttpServer().requestHandler(router::accept).listen(8080); } }
  • 21. Dependencies - Maven vert.x <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-dependencies</artifactId> <version>${vertx.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-core</artifactId> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-web</artifactId> </dependency>
  • 23. Verticle vert.x ● Small Vert Unit ● Regular Verticle ● Worker Verticle ● Multi Threaded Worker ● Automatic node discovery
  • 24. Reactor Pattern The reactor pattern is one implementation technique of event- driven architecture. In simple terms, it uses a single threaded event loop blocking on resource-emitting events and dispatches them to corresponding handlers and callbacks vert.x https://dzone.com/articles/understanding-reactor-pattern-thread-based-and-eve
  • 25. Regular Verticle - Event Loop vert.x
  • 26. Reactor Pattern - Vert.x vert.x
  • 28. Regular Verticle ● Golden Rule - Don’t block me! ● Event Loop (more than one) ● Multi Reactor Pattern ● High throughput (i.e http) vert.x
  • 29. public class EventLoopVerticle extends AbstractVerticle { public void start() { final Router router = Router.router(vertx); router.get("/test").handler(req -> { req.response() .putHeader("content-type","text/plain") .end(NormalProcess.process()); }); vertx.createHttpServer().requestHandler(router::accept).listen(8080); } } Regular Verticle - Example vert.x
  • 30. Don't do this !!!! vert.x public class EventLoopBlockerVerticle extends AbstractVerticle { public void start() { final Router router = Router.router(vertx); router.get("/test").handler(req -> { LongRunningProcess.longProcess(); final String date = LocalDateTime.now().toString(); req.response() .putHeader("content-type","text/plain") .end(String.format("TDC 2017 %s", date)); }); vertx.createHttpServer().requestHandler(router::accept).listen(8081); } }
  • 31. Worker Verticle ● Vert.x worker thread pool ● Execute blocking code ● They are never executed by more than one thread ● Background tasks vert.x
  • 32. Worker Verticle vert.x public class EventLoopBusVerticle extends AbstractVerticle { public void start() { this.vertx.deployVerticle(new BusVerticle(), new DeploymentOptions().setWorker(true)); this.vertx.deployVerticle(new RequestResourceVerticle()); } }
  • 33. Multi Threaded Verticle ● Based on worker verticle ● Can be executed concurrently by different threads ● Hard to code because you need to maintain states between verticles ● Specific needs vert.x
  • 34. Event Bus ● Nervous system of Vert.x ● Publish / Subscribe ● Point to Point ● Request Response ● Can be distributed vert.x
  • 36. Event Bus vert.x public class RequestResourceVerticle extends AbstractVerticle { private static final Logger LOGGER = LoggerFactory.getLogger(BusVerticle.class); public void start() { final EventBus eventBus = vertx.eventBus(); final Router router = Router.router(vertx); router.get("/test").handler(req -> { eventBus.send("data-stream", new JsonObject(), responseBus -> { if (responseBus.succeeded()) { req.response() .putHeader("content-type", "text/plain") .end(responseBus.result().body().toString()); } }); }); vertx.createHttpServer().requestHandler(router::accept).listen(8082); } }
  • 37. Service Discovery This component provides an infrastructure to publish and discover various resources, such as service proxies, HTTP endpoints, data sources…​ vert.x http://vertx.io/docs/vertx-service-discovery/java/
  • 38. Service Discovery Service provider Publish / Unpublish service record Update the status of a service vert.x http://vertx.io/docs/vertx-service-discovery/java/
  • 39. Service Discovery Service consumer Lookup service Bind to a selected service Release the service Listen for arrival and departure vert.x http://vertx.io/docs/vertx-service-discovery/java/
  • 40. Service Discovery - Backend vert.x final ServiceDiscoveryOptions serviceDiscoveryOptions = new ServiceDiscoveryOptions() .setBackendConfiguration( new JsonObject() .put("host", "127.0.0.1") .put("port", "6379") ); ServiceDiscovery sd = ServiceDiscovery.create(vertx,serviceDiscoveryOptions);
  • 41. Service Discovery - Publish vert.x vertx.createHttpServer().requestHandler(router::accept) .rxListen(8083) .flatMap(httpServer -> discovery .rxPublish(HttpEndpoint.createRecord("product", "localhost", 8083, "/"))) .subscribe(rec -> LOGGER.info("Product Service is published"));
  • 42. Service Discovery - Consumer vert.x final ServiceDiscoveryOptions serviceDiscoveryOptions = new ServiceDiscoveryOptions() .setBackendConfiguration( new JsonObject() .put("host", "127.0.0.1") .put("port", "6379") ); ServiceDiscovery discovery = ServiceDiscovery.create(vertx,serviceDiscoveryOptions); …. HttpEndpoint.rxGetWebClient(discovery, rec -> rec.getName().endsWith("product")) .flatMap(client -> client.get("/product/" + id).as(BodyCodec.string()).rxSend()) .subscribe(response -> req.response() .putHeader("content-type", "application/json") .end(response.body())); });
  • 43. Service Discovery ● Consul ● Kubernetes ● Redis ● Docker vert.x
  • 45. breaker.executeWithFallback( future -> { vertx.createHttpClient().getNow(8080, "localhost", "/", response -> { if (response.statusCode() != 200) { future.fail("HTTP error"); } else { response .exceptionHandler(future::fail) .bodyHandler(buffer -> { future.complete(buffer.toString()); }); } }); }, v -> { // Executed when the circuit is opened return "Hello"; }) .setHandler(ar -> { // Do something with the result }); Circuit Breaker vert.x
  • 46. Relational Database Integrations ● MySQL ● PostgreSQL ● JDBC vert.x
  • 47. NoSQL Database Integrations ● Redis ● MongoDB ● Cassandra ● OrientDB vert.x
  • 48. Messaging ● Kafka ● MQTT ● ZeroMQ ● RabbitMQ ● AMQP 1.0 vert.x
  • 51.

Editor's Notes

  1. Architectural style independently deployable services connected with reactive manifesto Smart endpoints dumb pipes
  2. Some challenges in this kind of architecture How to discover a lot of number of services One of this services fails..what happen??
  3. Circuit breakers are connected with Resilience Service discovery is connected with Responsive 3.3.0 Vert.x version
  4. Hystrix is a famous netflix implementation
  5. Eureka, zookeeper, consul and kubernetes
  6. Responsive = responsiveness means that problems may be detected quickly and dealt with effectively, they deliver a consistent quality of service. (Event Loop) Resilient = The system stays responsive in the face of failure. (Circuit Breaker) Elastic = The system stays responsive under varying workload. Reactive Systems can react to changes in the input rate by increasing or decreasing the resources allocated to service these inputs (Service Discovery) Message Driven = Reactive Systems rely on asynchronous message-passing to establish a boundary between components that ensures loose coupling, isolation and location transparency. (Event Bus)
  7. Architecture and Design Style Immutable data The data maybe are persistent between nodes In a message-driven system addressable recipients await the arrival of messages Specific destination
  8. Event is a signal by a component upon reaching a given state Callback based Increase vertical scalability ( multi core processors) Immutable data Event driven not Message Driven, events are signal and not persistent Thinking in process or program
  9. Vert.x was started by Tim Fox in 2011
  10. Vert.x was started by Tim Fox in 2011
  11. isn’ t a framework or library Is a open-source and eclipse foundation project Runnable jar Distributed by nature
  12. Non-blocking built on top netty library Java, Scala, Groovy, Kotlin, Ceylon and Javascript General purpose mean serve a static html files, serve an api, create a long running process or batch applications We can choose your DI framework, your favorite database or favorite cache for instance Zero annotation (NO BLACK MAGIC) , you must code and please use lambda is awesome
  13. Non-blocking built on top netty library Java, Scala, Groovy, Kotlin, Ceylon and Javascript General purpose mean serve a static html files, serve an api, create a long running process or batch applications We can choose your DI framework, your favorite database or favorite cache for instance Zero annotation (NO BLACK MAGIC) , you must code and please use lambda is awesome
  14. Non-blocking built on top netty library Java, Scala, Groovy, Kotlin, Ceylon and Javascript General purpose mean serve a static html files, serve an api, create a long running process or batch applications We can choose your DI framework, your favorite database or favorite cache for instance Zero annotation (NO BLACK MAGIC) , you must code and please use lambda is awesome
  15. Non-blocking built on top netty library Java, Scala, Groovy, Kotlin, Ceylon and Javascript General purpose mean serve a static html files, serve an api, create a long running process or batch applications We can choose your DI framework, your favorite database or favorite cache for instance Zero annotation (NO BLACK MAGIC) , you must code and please use lambda is awesome
  16. Add your dependencies and that is it
  17. Verticle can be standard, worker and multi threaded worker Event Bus can be clustered (hazelcast, zookeeper, infinispan and others)
  18. Verticle has some similarities with the Actor Model Standard: Verticles based upon the event loop model. As mentioned, Vert.x allows to configure the number of event loop instances. Worker: Verticles based upon the classical model. A pool of thread is defined, and each incoming request will consume one available thread. Multi-threaded worker: An extension of the basic worker model. A multi-threaded worker is managed by one single instance but can be executed concurrently by several threads. Extends AbstractVerticle
  19. Java application servers or web servers are implemented in Thread Based Architecture (blocking) Main actors are Reactor and Handlers Reactor - react to event to IO Events and dispatching to correct handlers Handler - perform the actual works, handlers must be non-blocking
  20. Remember this is one Reactor Pattern, but vert.x is multi reactor, in general is your CPU cores
  21. Remember this is one Reactor Pattern, but vert.x is multi reactor, in general is your CPU cores
  22. Default configuration is the events loops are the number of cores Similar nodejs but with JVM power
  23. This cause a block in event loop and your application is not answer anymore
  24. About the are never executed by more than one thread means easily to manage state, because runs in one thread Long running process for instance consumes a kafka stream
  25. Remember to set worker TRUE on deploy.
  26. Advanced feature and most application will have no need for them Because of the concurrency in these verticles you have to be very careful to keep the verticle in a consistent state using standard Java techniques for multi-threaded programming
  27. The event bus allows different parts of your application to communicate with each other irrespective of what language they are written in Can communicate with javascript in a browser Can be distributed hazelcast , infinispan and others Simple to use but powerfull, register handler, unregister, sending and publishing messages
  28. Address is a simple string, but keep in a mind in a kind of scheme is make helpfull Send - point to point messages direct Publish - all the handlers subscribed
  29. In this case we are using the redis backend for service discovery
  30. In this case we are using the javaRX wrappers for vert.x, for me is more easier than synchronous version Subscribe must be called to register
  31. Backend Configuration Get record reactive filtering