SlideShare a Scribd company logo
1 of 48
Download to read offline
Design Patterns para Microsserviços com MicroProfile
Víctor Orozco
4 de Dezembro de 2020
Nabenik
1
Design Patterns
Microserviçõs = Metapadrão arquitetural
Arquitetura que estrutura o aplicativo como um conjunto de serviços
colaborativos fracamente acoplados. Esta abordagem corresponde ao eixo Y do
scale cube. O objetivo final são sistemas reativos.
2
3
Application Server
• Transacionalidade distribuída (JTA/XA)
• Contratos (JNDI)
• Service discovery (JNDI)
• Deployment (EAR/Class Loaders/Dashboards)
• Métricas (JMX)
• Segurança (SoteriaRI/JACC)
4
Microserviçõs
Aplicativos Cloud Native
• Sistemas reativos
• 12 fatores Cloud Native
• Design patterns
• Domain Driven Design
• Microservice chassis e/ou service mesh
• Orquestração de contêineres
5
Microserviçõs = Metapadrão arquitetural
Cloud Native
• (Gostamos de ter) Sistemas reativos
• (É possível com a metodologia dos) 12 fatores Cloud Native
• (Usamos soluções testadas chamadas de) design patterns
• (Fragmentamos o sistema mediante) Domain Driven Design
• (Implementamos os serviços com frameworks) microservice chassis e/ou
service mesh
• (E fazemos deployment) mediante orquestração de contêineres
Os Dessign Patterns são uma linguagem comum para implementar e avaliar
plataformas Cloud Native.
6
7
Spring Boot/ MicroProfile/ Akka/ Vert.x
8
MicroProfile
A historia
Os patterns foram criados antes/junto com os chassis e antes do service
mesh/K8S
Créditos: Rafael Benevides
9
MicroProfile
Chassis
No ponto de vista dos design
patterns. Os frameworks ”cloud
native”são soluções para
problemas ”cross-cuting
concerns”.
Chassis EE
O MicroProfile é uma
especificação para chassis
fundamentada no Java/Jakarta EE
Figura 1: Créditos: Reza Rahman
10
MicroProfile
11
MicroProfile - Coreografia
Patterns complementarios - Event Sourcing, CQRS
12
MicroProfile - Orquestador
Patterns complementarios - SAGA
13
Cross-cutting concerns no mundo real
• Health checks & Metrics - Coletar metricas (Prometheus/Grafana) e
estabelecer regras no deployment
• Resilence & Fault Tolerance - Sobreposição entre service Mesh -e.g. Likerd,
Istio- e MicroProfile Fault Tolerance
• Configuration - Injeção de configuração no ambiente
• Authentication & Authorization - API Gateway + MicroProfile JWT
• Standarized documentation - OpenAPI + Swagger Server
• Tracing - MicroProfile Tracing + Zipkin
• Remote Procedure & Messaging - JAX-RS + MicroProfile Rest Client + K8S
service discovery
14
MicroProfile - APIs
EE + MicroProfile - Demo
Oracle Helidon (Chassis) + Oracle Kubernetes Engine
• Configuração
• Contrato e cliente REST
• Resiliência
• Deployment
• Health Check
• Metricas
15
Config
16
Config
17
Config
@Inject
@ConfigProperty(name = "omdbservice.url")
String omdbDaemonServiceUrl;
Ext. da configuração(VM, Docker, Kubernetes)
18
Config
@Inject
@ConfigProperty(name = "application.currency")
private String currency;
@Inject
@ConfigProperty(name = "application.list.maxSize",
defaultValue="10")
private Integer maxSize;
19
OpenAPI - REST
Documentação padronizada
@ApplicationPath("/api")
@OpenAPIDefinition(info = @Info(
title = "Example␣application",
version = "1.0.0",
contact = @Contact(
name = "Victor␣Orozoc",
email = "vorozco@nabenik.com",
url = "http://vorozco.com")
),
servers = {
@Server(url = "/example",
description = "localhost")
}
)
public class ApplicationConfig extends Application { 20
OpenAPI
Documentação padronizada
@GET @Path("/{key}")
@Operation(description = "Get␣the␣value␣for␣this␣key")
@APIResponses({
@APIResponse(responseCode = "200",
description = "Successful,␣returning␣the␣value")
})
@Produces(MediaType.TEXT_PLAIN)
public Response getConfigValue(@PathParam("key") String key)
21
OpenAPI
22
Fault Tolerance
23
Metrics
24
Fault Tolerance + Metrics
25
Fault tolerance
Regras e alternativas
• Circuit Breaker
• Bulkhead
• Retry
• Timeout
• Fallback
26
Fault tolerance - Retry
@Retry(delay = 400, maxDuration= 3200, jitter= 400, maxRetries = 10)
public Connection serviceA() {
...
}
@Retry(retryOn = {IOException.class})
public void serviceB() {
...
}
27
Fault tolerance - CircuitBreaker
@CircuitBreaker(successThreshold = 10,
requestVolumeThreshold = 4,
failureRatio=0.75,
delay = 1000)
public Connection serviceA() {
Connection conn = null;
conn = connectionService();
return conn;
}
28
Fault tolerance - Bulkhead
@Bulkhead(5)
public Connection serviceA() {
Connection conn = null;
conn = connectionService();
return conn;
}
@Asynchronous
@Bulkhead(value = 5, waitingTaskQueue = 8)
public Future<Connection> serviceA() {
Connection conn = null;
conn = connectionService();
return CompletableFuture.completedFuture(conn);
}
29
Fault tolerance - Fallback, Timeout
@GET
@Path("/{id:[a-z]*[0-9][0-9]*}")
@Fallback(fallbackMethod = "findByIdFallBack")
@Timeout(TIMEOUT)
public Response findById(@PathParam("id")
final String imdbId) {
...
}
public Response findByIdFallBack(@PathParam("id")
final String imdbId) {
...
}
30
Fault tolerance - Fallback Handler, Timeout
@GET
@Path("/{id:[a-z]*[0-9][0-9]*}")
@Fallback(MovieFindAllFallbackHandler.class)
@Timeout(TIMEOUT)
public Response findById(@PathParam("id")
final String imdbId) {
...
}
public class MovieFindAllFallbackHandler
implements FallbackHandler<List> {
@Override
public List handle(final ExecutionContext context) {
return Stream.of("Star␣Wars",
"The␣Matrix", "Cantinflas").collect(toList());
}
} 31
Metrics
• JSON or OpenMetrics (Prometheus)
• Vendor
• Base
• Application
Opções
• Counted
• Gauge
• Metered
• Timed
• Histogram
32
Metrics - Counted
@Inject
@Metric
Counter failedQueries;
@GET
@Path("/{id:[a-z]*[0-9][0-9]*}")
@Fallback(fallbackMethod = "findByIdFallBack")
@Timeout(TIMEOUT)
public Response findById(@PathParam("id")
final String imdbId) {
...
}
public Response findByIdFallBack(@PathParam("id")
final String imdbId) {
...
failedQueries.inc(); 33
Metrics - Gauge
Inc-dec
@Gauge(unit = "ExternalDatabases",name = "movieDatabases", absolute = true)
public long getDatabases() {
return 99; //Any value
}
/metrics/application/movieDatabases
34
Metrics - Metered
Events rate
@Metered(name = "moviesRetrieved",
unit = MetricUnits.MINUTES,
description = "Metrics␣to␣monitor␣movies",
absolute = true)
public Response findExpandedById(
@PathParam("id") final Long id)
/metrics/application/movieDatabases
35
Metrics- Timed
Performance
@Timed(name = "moviesDelay",
description = "Time␣to␣retrieve␣a␣movie",
unit = MetricUnits.MINUTES,
absolute = true)
public Response findExpandedById(
@PathParam("id") final Long id)
/metrics/application/moviesDelay
36
Metrics - Histogram
Distribuciones
@Inject
MetricRegistry registry;
@POST
@Path("/add/{attendees}")
public Response addAttendees(
@PathParam("attendees") Long attendees) {
Metadata metadata =
new Metadata("matrix␣attendees",
MetricType.HISTOGRAM);
Histogram histogram =
registry.histogram(metadata);
histogram.update(attendees);
return Response.ok().build();
} 37
Health Check
38
Health Check
@Override
public HealthCheckResponse call() {
return HealthCheckResponse.named("TaVivoAinda")
.withData("key1", "val1")
.withData("key2", "val2")
.up()
.build();
}
39
JWT
40
JWT
@LoginConfig(authMethod = "MP-JWT")
public class ApplicationConfig extends Application {
}
@Inject
private JsonWebToken jwtPrincipal;
@Inject
@Claim("email")
private String email;
41
TypeSafe
42
TypeSafe
@Path("/playlist")
@Consumes("application/json")
public interface MusicPlaylistService {
@GET
List<String> getPlaylistNames();
@PUT
@Path("/{playlistName}")
long updatePlayList(@PathParam("playlistName")
String name,
List<Song> playlist)
throws UnknownPlaylistException;
}
43
12 fatores cloud native (Heroku)
Microprofile
• Config
• Backing service
• Disposability
Cloud
• Codebase (Git-Flow)
• Dependencies (Maven)
• Build, Release, Run
• Processes (Pipelines)
• Port binding
• Concurrency (Docker - k8s)
• Dev / Prod parity
• Logs
• Admin process
44
Víctor Orozco
• vorozco@nabenik.com
• @tuxtor
• http://vorozco.com
• http://tuxtor.shekalug.org
This work is licensed under
Creative Commons Attribution-
NonCommercial-ShareAlike 3.0
Guatemala (CC BY-NC-SA 3.0 GT).
45

More Related Content

What's hot

OpenStack Neutron Reverse Engineered
OpenStack Neutron Reverse EngineeredOpenStack Neutron Reverse Engineered
OpenStack Neutron Reverse Engineered
openstackindia
 
OpenStack Nova Scheduler
OpenStack Nova Scheduler OpenStack Nova Scheduler
OpenStack Nova Scheduler
Peeyush Gupta
 

What's hot (19)

Leveraging the Power of containerd Events - Evan Hazlett
Leveraging the Power of containerd Events - Evan HazlettLeveraging the Power of containerd Events - Evan Hazlett
Leveraging the Power of containerd Events - Evan Hazlett
 
GlassFish v2.1
GlassFish v2.1GlassFish v2.1
GlassFish v2.1
 
Scale Kubernetes to support 50000 services
Scale Kubernetes to support 50000 servicesScale Kubernetes to support 50000 services
Scale Kubernetes to support 50000 services
 
Policy-based Resource Placement
Policy-based Resource PlacementPolicy-based Resource Placement
Policy-based Resource Placement
 
OpenStack Contribution Workflow
OpenStack Contribution WorkflowOpenStack Contribution Workflow
OpenStack Contribution Workflow
 
Java and Containers: What's there to think about? | DevNation Tech Talk
Java and Containers: What's there to think about? | DevNation Tech TalkJava and Containers: What's there to think about? | DevNation Tech Talk
Java and Containers: What's there to think about? | DevNation Tech Talk
 
OpenDaylight OpenStack Integration
OpenDaylight OpenStack IntegrationOpenDaylight OpenStack Integration
OpenDaylight OpenStack Integration
 
VietOpenStack meetup 7th High Performance VM
VietOpenStack meetup 7th High Performance VMVietOpenStack meetup 7th High Performance VM
VietOpenStack meetup 7th High Performance VM
 
Introduction to OpenStack Cinder
Introduction to OpenStack CinderIntroduction to OpenStack Cinder
Introduction to OpenStack Cinder
 
Running Legacy Applications with Containers
Running Legacy Applications with ContainersRunning Legacy Applications with Containers
Running Legacy Applications with Containers
 
Development with Vert.x: an event-driven application framework for the JVM
Development with Vert.x: an event-driven application framework for the JVMDevelopment with Vert.x: an event-driven application framework for the JVM
Development with Vert.x: an event-driven application framework for the JVM
 
How to Integrate Kubernetes in OpenStack
 How to Integrate Kubernetes in OpenStack  How to Integrate Kubernetes in OpenStack
How to Integrate Kubernetes in OpenStack
 
containerd and CRI
containerd and CRIcontainerd and CRI
containerd and CRI
 
Container orchestration and microservices world
Container orchestration and microservices worldContainer orchestration and microservices world
Container orchestration and microservices world
 
Get a Taste of 1 k+ Nodes by a Handful of Servers
Get a Taste of 1 k+ Nodes by a Handful of Servers Get a Taste of 1 k+ Nodes by a Handful of Servers
Get a Taste of 1 k+ Nodes by a Handful of Servers
 
OpenStack Neutron Reverse Engineered
OpenStack Neutron Reverse EngineeredOpenStack Neutron Reverse Engineered
OpenStack Neutron Reverse Engineered
 
OpenStack Nova - Developer Introduction
OpenStack Nova - Developer IntroductionOpenStack Nova - Developer Introduction
OpenStack Nova - Developer Introduction
 
AdaCore Paris Tech Day 2016: Arnaud Chalet - GNAT Pro Roadmap
AdaCore Paris Tech Day 2016: Arnaud Chalet - GNAT Pro RoadmapAdaCore Paris Tech Day 2016: Arnaud Chalet - GNAT Pro Roadmap
AdaCore Paris Tech Day 2016: Arnaud Chalet - GNAT Pro Roadmap
 
OpenStack Nova Scheduler
OpenStack Nova Scheduler OpenStack Nova Scheduler
OpenStack Nova Scheduler
 

Similar to Design Patterns para Microsserviços com MicroProfile

Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
Jiayun Zhou
 

Similar to Design Patterns para Microsserviços com MicroProfile (20)

Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...
Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...
Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...
 
Se lancer dans l'aventure microservices avec Spring Cloud - Julien Roy
Se lancer dans l'aventure microservices avec Spring Cloud - Julien RoySe lancer dans l'aventure microservices avec Spring Cloud - Julien Roy
Se lancer dans l'aventure microservices avec Spring Cloud - Julien Roy
 
(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++
 
Cloud nativeworkshop
Cloud nativeworkshopCloud nativeworkshop
Cloud nativeworkshop
 
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexusMicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
 
Hazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMSHazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMS
 
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
 
Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020
 
Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020
 
Cloud Native Spring - The role of Spring Cloud after Kubernetes became a main...
Cloud Native Spring - The role of Spring Cloud after Kubernetes became a main...Cloud Native Spring - The role of Spring Cloud after Kubernetes became a main...
Cloud Native Spring - The role of Spring Cloud after Kubernetes became a main...
 
Clean Architecture @ Taxibeat
Clean Architecture @ TaxibeatClean Architecture @ Taxibeat
Clean Architecture @ Taxibeat
 
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
Simplify Cloud Applications using Spring Cloud
Simplify Cloud Applications using Spring CloudSimplify Cloud Applications using Spring Cloud
Simplify Cloud Applications using Spring Cloud
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
 
Smart Contract Testing
Smart Contract TestingSmart Contract Testing
Smart Contract Testing
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
 
Microservices and modularity with java
Microservices and modularity with javaMicroservices and modularity with java
Microservices and modularity with java
 
Eclipse MicroProfile para el desarrollador ocupado
Eclipse MicroProfile para el desarrollador ocupadoEclipse MicroProfile para el desarrollador ocupado
Eclipse MicroProfile para el desarrollador ocupado
 
Présentation et bonnes pratiques du pattern MVVM - MIC Belgique
Présentation et bonnes pratiques du pattern MVVM - MIC BelgiquePrésentation et bonnes pratiques du pattern MVVM - MIC Belgique
Présentation et bonnes pratiques du pattern MVVM - MIC Belgique
 

More from Víctor Leonel Orozco López

More from Víctor Leonel Orozco López (20)

Introducción al análisis de datos
Introducción al análisis de datosIntroducción al análisis de datos
Introducción al análisis de datos
 
From traditional to GitOps
From traditional to GitOpsFrom traditional to GitOps
From traditional to GitOps
 
Iniciando microservicios reales con JakartaEE/MicroProfile y arquetipos de Maven
Iniciando microservicios reales con JakartaEE/MicroProfile y arquetipos de MavenIniciando microservicios reales con JakartaEE/MicroProfile y arquetipos de Maven
Iniciando microservicios reales con JakartaEE/MicroProfile y arquetipos de Maven
 
Desde la TV, hasta la nube, el ecosistema de Java en 26 años
Desde la TV, hasta la nube, el ecosistema de Java en 26 añosDesde la TV, hasta la nube, el ecosistema de Java en 26 años
Desde la TV, hasta la nube, el ecosistema de Java en 26 años
 
Bootstraping real world Jakarta EE/MicroProfile microservices with Maven Arch...
Bootstraping real world Jakarta EE/MicroProfile microservices with Maven Arch...Bootstraping real world Jakarta EE/MicroProfile microservices with Maven Arch...
Bootstraping real world Jakarta EE/MicroProfile microservices with Maven Arch...
 
Tolerancia a fallas, service mesh y chassis
Tolerancia a fallas, service mesh y chassisTolerancia a fallas, service mesh y chassis
Tolerancia a fallas, service mesh y chassis
 
Explorando los objetos centrales de Kubernetes con Oracle Cloud
Explorando los objetos centrales de Kubernetes con Oracle CloudExplorando los objetos centrales de Kubernetes con Oracle Cloud
Explorando los objetos centrales de Kubernetes con Oracle Cloud
 
Introducción a GraalVM Native para aplicaciones JVM
Introducción a GraalVM Native para aplicaciones JVMIntroducción a GraalVM Native para aplicaciones JVM
Introducción a GraalVM Native para aplicaciones JVM
 
Desarrollo moderno con DevOps y Cloud Native
Desarrollo moderno con DevOps y Cloud NativeDesarrollo moderno con DevOps y Cloud Native
Desarrollo moderno con DevOps y Cloud Native
 
Gestión de proyectos con Maven
Gestión de proyectos con MavenGestión de proyectos con Maven
Gestión de proyectos con Maven
 
MicroProfile benefits for your monolithic applications
MicroProfile benefits for your monolithic applicationsMicroProfile benefits for your monolithic applications
MicroProfile benefits for your monolithic applications
 
Actualizando aplicaciones empresariales en Java desde Java 8 on premise hasta...
Actualizando aplicaciones empresariales en Java desde Java 8 on premise hasta...Actualizando aplicaciones empresariales en Java desde Java 8 on premise hasta...
Actualizando aplicaciones empresariales en Java desde Java 8 on premise hasta...
 
Actualizando aplicaciones empresariales en Java desde Java 8 on premise hasta...
Actualizando aplicaciones empresariales en Java desde Java 8 on premise hasta...Actualizando aplicaciones empresariales en Java desde Java 8 on premise hasta...
Actualizando aplicaciones empresariales en Java desde Java 8 on premise hasta...
 
Consejos y el camino del desarrollador de software
Consejos y el camino del desarrollador de softwareConsejos y el camino del desarrollador de software
Consejos y el camino del desarrollador de software
 
Seguridad de aplicaciones Java/JakartaEE con OWASP Top 10
Seguridad de aplicaciones Java/JakartaEE con OWASP Top 10Seguridad de aplicaciones Java/JakartaEE con OWASP Top 10
Seguridad de aplicaciones Java/JakartaEE con OWASP Top 10
 
Introducción a Kotlin para desarrolladores Java
Introducción a Kotlin para desarrolladores JavaIntroducción a Kotlin para desarrolladores Java
Introducción a Kotlin para desarrolladores Java
 
Programación con ECMA6 y TypeScript
Programación con ECMA6 y TypeScriptProgramación con ECMA6 y TypeScript
Programación con ECMA6 y TypeScript
 
Empaquetando aplicaciones Java con Docker y Kubernetes
Empaquetando aplicaciones Java con Docker y KubernetesEmpaquetando aplicaciones Java con Docker y Kubernetes
Empaquetando aplicaciones Java con Docker y Kubernetes
 
MicroProfile benefits for monolitic applications
MicroProfile benefits for monolitic applicationsMicroProfile benefits for monolitic applications
MicroProfile benefits for monolitic applications
 
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguajeKotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
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
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 

Design Patterns para Microsserviços com MicroProfile

  • 1. Design Patterns para Microsserviços com MicroProfile Víctor Orozco 4 de Dezembro de 2020 Nabenik 1
  • 3. Microserviçõs = Metapadrão arquitetural Arquitetura que estrutura o aplicativo como um conjunto de serviços colaborativos fracamente acoplados. Esta abordagem corresponde ao eixo Y do scale cube. O objetivo final são sistemas reativos. 2
  • 4. 3
  • 5. Application Server • Transacionalidade distribuída (JTA/XA) • Contratos (JNDI) • Service discovery (JNDI) • Deployment (EAR/Class Loaders/Dashboards) • Métricas (JMX) • Segurança (SoteriaRI/JACC) 4
  • 6. Microserviçõs Aplicativos Cloud Native • Sistemas reativos • 12 fatores Cloud Native • Design patterns • Domain Driven Design • Microservice chassis e/ou service mesh • Orquestração de contêineres 5
  • 7. Microserviçõs = Metapadrão arquitetural Cloud Native • (Gostamos de ter) Sistemas reativos • (É possível com a metodologia dos) 12 fatores Cloud Native • (Usamos soluções testadas chamadas de) design patterns • (Fragmentamos o sistema mediante) Domain Driven Design • (Implementamos os serviços com frameworks) microservice chassis e/ou service mesh • (E fazemos deployment) mediante orquestração de contêineres Os Dessign Patterns são uma linguagem comum para implementar e avaliar plataformas Cloud Native. 6
  • 9. 8
  • 11. A historia Os patterns foram criados antes/junto com os chassis e antes do service mesh/K8S Créditos: Rafael Benevides 9
  • 12. MicroProfile Chassis No ponto de vista dos design patterns. Os frameworks ”cloud native”são soluções para problemas ”cross-cuting concerns”. Chassis EE O MicroProfile é uma especificação para chassis fundamentada no Java/Jakarta EE Figura 1: Créditos: Reza Rahman 10
  • 14. MicroProfile - Coreografia Patterns complementarios - Event Sourcing, CQRS 12
  • 15. MicroProfile - Orquestador Patterns complementarios - SAGA 13
  • 16. Cross-cutting concerns no mundo real • Health checks & Metrics - Coletar metricas (Prometheus/Grafana) e estabelecer regras no deployment • Resilence & Fault Tolerance - Sobreposição entre service Mesh -e.g. Likerd, Istio- e MicroProfile Fault Tolerance • Configuration - Injeção de configuração no ambiente • Authentication & Authorization - API Gateway + MicroProfile JWT • Standarized documentation - OpenAPI + Swagger Server • Tracing - MicroProfile Tracing + Zipkin • Remote Procedure & Messaging - JAX-RS + MicroProfile Rest Client + K8S service discovery 14
  • 18. EE + MicroProfile - Demo Oracle Helidon (Chassis) + Oracle Kubernetes Engine • Configuração • Contrato e cliente REST • Resiliência • Deployment • Health Check • Metricas 15
  • 21. Config @Inject @ConfigProperty(name = "omdbservice.url") String omdbDaemonServiceUrl; Ext. da configuração(VM, Docker, Kubernetes) 18
  • 22. Config @Inject @ConfigProperty(name = "application.currency") private String currency; @Inject @ConfigProperty(name = "application.list.maxSize", defaultValue="10") private Integer maxSize; 19
  • 23. OpenAPI - REST Documentação padronizada @ApplicationPath("/api") @OpenAPIDefinition(info = @Info( title = "Example␣application", version = "1.0.0", contact = @Contact( name = "Victor␣Orozoc", email = "vorozco@nabenik.com", url = "http://vorozco.com") ), servers = { @Server(url = "/example", description = "localhost") } ) public class ApplicationConfig extends Application { 20
  • 24. OpenAPI Documentação padronizada @GET @Path("/{key}") @Operation(description = "Get␣the␣value␣for␣this␣key") @APIResponses({ @APIResponse(responseCode = "200", description = "Successful,␣returning␣the␣value") }) @Produces(MediaType.TEXT_PLAIN) public Response getConfigValue(@PathParam("key") String key) 21
  • 28. Fault Tolerance + Metrics 25
  • 29. Fault tolerance Regras e alternativas • Circuit Breaker • Bulkhead • Retry • Timeout • Fallback 26
  • 30. Fault tolerance - Retry @Retry(delay = 400, maxDuration= 3200, jitter= 400, maxRetries = 10) public Connection serviceA() { ... } @Retry(retryOn = {IOException.class}) public void serviceB() { ... } 27
  • 31. Fault tolerance - CircuitBreaker @CircuitBreaker(successThreshold = 10, requestVolumeThreshold = 4, failureRatio=0.75, delay = 1000) public Connection serviceA() { Connection conn = null; conn = connectionService(); return conn; } 28
  • 32. Fault tolerance - Bulkhead @Bulkhead(5) public Connection serviceA() { Connection conn = null; conn = connectionService(); return conn; } @Asynchronous @Bulkhead(value = 5, waitingTaskQueue = 8) public Future<Connection> serviceA() { Connection conn = null; conn = connectionService(); return CompletableFuture.completedFuture(conn); } 29
  • 33. Fault tolerance - Fallback, Timeout @GET @Path("/{id:[a-z]*[0-9][0-9]*}") @Fallback(fallbackMethod = "findByIdFallBack") @Timeout(TIMEOUT) public Response findById(@PathParam("id") final String imdbId) { ... } public Response findByIdFallBack(@PathParam("id") final String imdbId) { ... } 30
  • 34. Fault tolerance - Fallback Handler, Timeout @GET @Path("/{id:[a-z]*[0-9][0-9]*}") @Fallback(MovieFindAllFallbackHandler.class) @Timeout(TIMEOUT) public Response findById(@PathParam("id") final String imdbId) { ... } public class MovieFindAllFallbackHandler implements FallbackHandler<List> { @Override public List handle(final ExecutionContext context) { return Stream.of("Star␣Wars", "The␣Matrix", "Cantinflas").collect(toList()); } } 31
  • 35. Metrics • JSON or OpenMetrics (Prometheus) • Vendor • Base • Application Opções • Counted • Gauge • Metered • Timed • Histogram 32
  • 36. Metrics - Counted @Inject @Metric Counter failedQueries; @GET @Path("/{id:[a-z]*[0-9][0-9]*}") @Fallback(fallbackMethod = "findByIdFallBack") @Timeout(TIMEOUT) public Response findById(@PathParam("id") final String imdbId) { ... } public Response findByIdFallBack(@PathParam("id") final String imdbId) { ... failedQueries.inc(); 33
  • 37. Metrics - Gauge Inc-dec @Gauge(unit = "ExternalDatabases",name = "movieDatabases", absolute = true) public long getDatabases() { return 99; //Any value } /metrics/application/movieDatabases 34
  • 38. Metrics - Metered Events rate @Metered(name = "moviesRetrieved", unit = MetricUnits.MINUTES, description = "Metrics␣to␣monitor␣movies", absolute = true) public Response findExpandedById( @PathParam("id") final Long id) /metrics/application/movieDatabases 35
  • 39. Metrics- Timed Performance @Timed(name = "moviesDelay", description = "Time␣to␣retrieve␣a␣movie", unit = MetricUnits.MINUTES, absolute = true) public Response findExpandedById( @PathParam("id") final Long id) /metrics/application/moviesDelay 36
  • 40. Metrics - Histogram Distribuciones @Inject MetricRegistry registry; @POST @Path("/add/{attendees}") public Response addAttendees( @PathParam("attendees") Long attendees) { Metadata metadata = new Metadata("matrix␣attendees", MetricType.HISTOGRAM); Histogram histogram = registry.histogram(metadata); histogram.update(attendees); return Response.ok().build(); } 37
  • 42. Health Check @Override public HealthCheckResponse call() { return HealthCheckResponse.named("TaVivoAinda") .withData("key1", "val1") .withData("key2", "val2") .up() .build(); } 39
  • 44. JWT @LoginConfig(authMethod = "MP-JWT") public class ApplicationConfig extends Application { } @Inject private JsonWebToken jwtPrincipal; @Inject @Claim("email") private String email; 41
  • 46. TypeSafe @Path("/playlist") @Consumes("application/json") public interface MusicPlaylistService { @GET List<String> getPlaylistNames(); @PUT @Path("/{playlistName}") long updatePlayList(@PathParam("playlistName") String name, List<Song> playlist) throws UnknownPlaylistException; } 43
  • 47. 12 fatores cloud native (Heroku) Microprofile • Config • Backing service • Disposability Cloud • Codebase (Git-Flow) • Dependencies (Maven) • Build, Release, Run • Processes (Pipelines) • Port binding • Concurrency (Docker - k8s) • Dev / Prod parity • Logs • Admin process 44
  • 48. Víctor Orozco • vorozco@nabenik.com • @tuxtor • http://vorozco.com • http://tuxtor.shekalug.org This work is licensed under Creative Commons Attribution- NonCommercial-ShareAlike 3.0 Guatemala (CC BY-NC-SA 3.0 GT). 45