SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
telestax
 

Tendances (20)

Weaving Through the Mesh: Making Sense of Istio and Overlapping Technologies
Weaving Through the Mesh: Making Sense of Istio and Overlapping TechnologiesWeaving Through the Mesh: Making Sense of Istio and Overlapping Technologies
Weaving Through the Mesh: Making Sense of Istio and Overlapping Technologies
 
Lockless Producer Consumer Threads: Asynchronous Communications Made Easy
Lockless Producer Consumer Threads: Asynchronous Communications Made EasyLockless Producer Consumer Threads: Asynchronous Communications Made Easy
Lockless Producer Consumer Threads: Asynchronous Communications Made Easy
 
Visual C++ project model
Visual C++ project modelVisual C++ project model
Visual C++ project model
 
My way to clean android V2
My way to clean android V2My way to clean android V2
My way to clean android V2
 
Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4
 
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
 
Qt for beginners
Qt for beginnersQt for beginners
Qt for beginners
 
OrientDB - The 2nd generation of (multi-model) NoSQL
OrientDB - The 2nd generation of  (multi-model) NoSQLOrientDB - The 2nd generation of  (multi-model) NoSQL
OrientDB - The 2nd generation of (multi-model) NoSQL
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QML
 
Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo...
Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo...Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo...
Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo...
 
Event Sourcing - what could possibly go wrong?
Event Sourcing - what could possibly go wrong?Event Sourcing - what could possibly go wrong?
Event Sourcing - what could possibly go wrong?
 
Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2
 
YaJUG: What's new in GWT2
YaJUG: What's new in GWT2YaJUG: What's new in GWT2
YaJUG: What's new in GWT2
 
Assic 12th Lecture
Assic 12th LectureAssic 12th Lecture
Assic 12th Lecture
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programming
 
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
 
Best Practices in Qt Quick/QML - Part 3
Best Practices in Qt Quick/QML - Part 3Best Practices in Qt Quick/QML - Part 3
Best Practices in Qt Quick/QML - Part 3
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part III
 
Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4
 
GradleFX
GradleFXGradleFX
GradleFX
 

Similaire à Vertx SouJava

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
Hugo Hamon
 

Similaire à Vertx SouJava (20)

TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
 
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
 

Dernier

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Dernier (20)

WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 

Vertx SouJava

  • 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.

Notes de l'éditeur

  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