SlideShare une entreprise Scribd logo
1  sur  43
Emily Jiang, Java Champion
Senior Technical Staff Member, IBM
Liberty Microservice Architect, Advocate
Senior Lead for MicroProfile and CDI
@emilyfhjiang
Creating a cloud-native microservice
– which programming mode should I use?
Characteristics
Specs, APIs, TCKs
Community Driven
Lightweight, Iterative
Processes
No Reference
Impls!
MicroProfile 1.0 (Fall 2016)
jaxrs-2.0
cdi-1.2
jsonp-1.0
MicroProfile 1.1 (August
2017)
microProfile-1.0
mpConfig-1.0
MicroProfile 1.2 (Sept 2017)
microProfile-1.1
mpConfig-1.1
mpFaultTolerance-1.0
mpHealth-1.0
mpMetrics-1.0
mpJwt-1.0
2017
2018
MicroProfile 1.3 (Dec 2017)
MicroProfile 1.2
mpConfig-1.2
mpMetrics-1.1
mpOpenApi-1.0
mpOpenTracing-1.0
mpRestClient-1.0
MicroProfile 1.4 (June 2018)
MicroProfile 1.3
mpConfig-1.3
mpFaultTolerance-1.1
mpJwt-1.1
mpOpenTracing-1.1
mpRestClient-1.1
2019
MicroProfile 2.0.1 (July
2018)
MicroProfile 1.4
jaxrs-2.1 // Java EE 8
cdi-2.0 // Java EE 8
jsonp-1.1 // Java EE 8
jsonb-1.0 // Java EE 8
MicroProfile 2.1 (Oct 2018)
MicroProfile 2.0
mpOpenTracing-1.2
MicroProfile 2.2 (Feb 2019)
Fault Tolerance 2.0
OpenAPI 1.1
OpenTracing 1.3
Rest Client 1.2
Jan
19.0.0.8
19.0.0.7 19.0.0.9
MicroProfile 3.0 (June
2019)
Metrics 2.0
Health Check 2.0
Rest Client 1.3
CDI 2.0
Latest release
JAX-RS 2.1 JSON-P 1.1
MicroProfile 3.0
JSON-B 1.0
Fault
Tolerance
2.0
Metrics 2.0
JWT
Propagation
1.1
Health
Check 2.0
Open
Tracing 1.3
Open API
1.1
Rest Client
1.3
Config 1.3
20+
Component
Releases!
9 Platform
Releases!
MicroProfile
3.0
Reactive
Streams
Operators
Reactive
Messaging
Context
Propagation
Standalone releases
Open specifications
Wide vendor support
REST services
OpenAPI support
Security
Fault Tolerance
Configuration
Metrics
Health
Open Tracing
https://wiki.eclipse.org/MicroProfile/Implementation
Implementations
Spring MicroProfile
Getting started
Starter https://start.spring.io/ https://start.microprofile.io/
REST
REST Service Spring MVC JAX-RS
Dependency Injection Spring IoC & DI CDI
API Documentation Spring REST Docs MP Open API
REST Client Spring MVC
Feign
MP REST Client
JSON Binding/Processing Bring Your Own Llibrary
Jackson, JSON-B
JSON-B
JSON-P
Reactive
Reactive Spring Reactor
Use Kafka APIs to connect
with Kafka
MicroProfile Reactive Streams
Operator, RxJava
MicroProfile Reactive
Messaging
Handling 100s of Services
Configuration Spring Boot Config
Spring Cloud Config
MP Config
Fault Tolerance Netflix Hystrix MP Fault Tolerance
Security Spring Security
Spring Cloud Security
EE Security
MP JWT Propagation
Operation Focus
Health Checks Spring Boot Actuator MP Health Check
Metrics Spring Boot Actuator MP Metrics
Distributed Tracing Spring Cloud Sleuth MP Open Tracing
Capabilities
https://start.microprofile.io
Getting started
https://start.spring.io/
There’s a good chance you’ll use REST APIs
B
REST
REST Services
@ApplicationPath("/rest")
public class CatalogApplication
extends Application {
}
@Path("/items")
@Produces(MediaType.APPLICATION_J
SON)
public class CatalogService {..}
@GET
public List<Item> getInventory()
{…}
@GET
@Path("{id}")
public Response
getById(@PathParam("id") long id)
{…}
@SpringBootApplication
public class Application {
public static void main(String[] args)
{
SpringApplication.run(Application.class,
args);}
}
@RestController
public class CatalogController {..}
@RequestMapping(value = "/items", method
= RequestMethod.GET)
@ResponseBody
List<Item> getInventory() {..}
@RequestMapping(value = "/items/{id}",
method = RequestMethod.GET)
ResponseEntity<?> getById(@PathVariable
long id) {…}
Spring MicroProfile
JAX-RS in MicroProfile
B
@ApplicationPath("System")
public class SystemApplication extends
Application {}
@Path("properties")
public class PropertiesResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getProperties() {…}
}
B
Dependency Injection
Dependency Injection
@ApplicationPath("/rest")
public class JaxrsApplication extends
Application {
@Inject
private InventoryRefreshTask
refreshTask;
@ApplicationScoped
public class InventoryRefreshTask {
…
}
@SpringBootApplication
public class Application {
@Autowired
private InventoryRefreshTask
refreshTask;
Spring MicroProfile B
CDI for MicroProfile
A
public class InventoryManager {
@Inject
private SystemClient systemClient;
…
}
Document API
A B
© 2018 IBM Corporation
Document APIs in Spring
1
8
1. Define the dependencies
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-core</artifactId>
<scope>test</scope> </dependency>
2. Define your Rest service
--------------------
@RestController
public class CatalogController {
@RequestMapping("/")
public @ResponseBody String index() {
return "Greetings from Catalog Service !";
}
}
-----------------
3. Define all necessary test classes
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CatalogController.class)
@WebAppConfiguration
public class CatalogControllerTest {
@Rule public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets");
private MockMvc mockMvc;
@Autowired private WebApplicationContext context;
@Before public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(context) .apply(documentationConfiguration(restDocumentation)) .build();
}
4. Use alwaysDo(), responseFileds(), requestPayload(), links(),
fieldWithPath(), requestParameters(), pathParameters() to
document
@Test
public void crudDeleteExample() throws Exception {
this.mockMvc.perform(delete("/crud/{id}", 10)).andExpect(status().isOk())
.andDo(document("crud-delete-example",
pathParameters(
parameterWithName("id").description("The id of the input to delete")
)));
}
MicroProfile OpenAPI
A B
openapi: 3.0.0
info:
title: Inventory App
description: App for storing JVM system properties of various
hosts.
license:
name: Eclipse Public License - v 1.0
url: https://www.eclipse.org/legal/epl-v10.html
version: "1.0"
servers: - url: http://localhost:{port} description: Simple Open
Liberty.
variables:
port:
description: Server HTTP port.
default: "9080"
paths:
/inventory/systems:
get:
summary: List inventory contents.
description: Returns the currently stored host:properties pairs
in the inventory.
operationId: listContents
responses:
200:
description: host:properties pairs stored in the inventory.
content:
application/json:
schema:
$ref: '#/components/schemas/InventoryList’
….
http://localhost:9080/openapi/ui
@GET
@Produces(MediaType.APPLICATION_JSON)
@APIResponse(
responseCode = "200",
description = "host:properties pairs stored in the inventory.",
content = @Content( mediaType = "application/json",
schema = @Schema( type = SchemaType.OBJECT,
implementation = InventoryList.class)))
@Operation( summary = "List inventory contents.",
description = "Returns the stored host:properties pairs.")
public InventoryList listContents() { return manager.list(); }
Rest Clients
BA
REST Clients
2
1
@Dependent
@RegisterRestClient
@RegisterProvider(InventoryResponseExceptionMapper.class)
// Optional
public interface InventoryServiceClient {
@GET
@Produces(MediaType.APPLICATION_JSON)
List<Item> getAllItems() throws UnknownUrlException,
ServiceNotReadyException;
}
@Inject
@RestClient
private InventoryServiceClient invClient;
final List<Item> allItems = invClient.getAllItems();
@FeignClient(name="inventory-service",
url="${inventoryService.url}")
public interface InventoryServiceClient {
@RequestMapping(method=RequestMethod.GET,
value="/micro/inventory",
produces={MediaType.APPLICATION_JSON_VALUE})
List<Item> getAllItems();
}
@EnableFeignClients
public class Application {
@Autowired
private InventoryServiceClient invClient;
final List<Item> allItems = invClient.getAllItems();
Spring MicroProfile
MicroProfile REST Client
BA
@Inject
@RestClient
private SystemClient
defaultRestClient;
@Dependent
@RegisterRestClient
@RegisterProvider(UnknownUrlExceptionMapper.class)
@Path("/properties")
public interface SystemClient {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Properties getProperties() throws
UnknownUrlException, ProcessingException;
}
io.openliberty.guides.inventory.client.SystemClient/mp-rest/url=http://localhost:9080/system
JSON-B & JSON-P
A B
JSON Binding/Processing
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(artists);
import
com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
final ObjectMapper objMapper = new ObjectMapper();
jsonString = objMapper.writeValueAsString(item);
// or
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(artists);
MicroProfile
Spring
JSON-B & JSON-P in MicroProfile
A B
...
@GET
@Produces(MediaType.APPLICATION_JSON)
public InventoryList listContents() {
return manager.list();
}
public class InventoryList {
private List<SystemData> systems;
public InventoryList(List<SystemData> systems) {
this.systems = systems;
}
public List<SystemData> getSystems() {
return systems;
}
public int getTotal() {
return systems.size();
}
}
Reactive
MicroProfile Reactive Stream Operators
to work with Reactive Streams
Can also use RxJava
MicroProfile Reactive Messaging
Spring
MicroProfile
Use Spring Reactor
Directly use Kafka APIs or Spring boot
annotations to interact with Kafka
streams
@KafkaListener(topics = "users", groupId = "group_id")
public void consume(String message){
…
}
@Autowired
private KafkaTemplate<String,String> kafkaTemplate;
public void sendMessage(String message){
logger.info(String.format("$$ -> Producing message
--> %s",message));
this.kafkaTemplate.send(TOPIC,message);
}
Handling 100s of Services
Configuration
A B
Configuration
2
9
# Elasticsearch
elasticsearch_url=http://es-catalog-
elasticsearch:9200
elasticsearch_index=micro
elasticsearch_doc_type=items
=====================
Config config = ConfigProvider.getConfig();
private String url =
config.getValue("elasticsearch_url",
String.class);
=====================
@Inject
@ConfigProperty(name=“elasticsearch_url”)
String url;
# Elasticsearch
elasticsearch:
url: http://localhost:9200
user:
password:
index: micro
doc_type: items
=====================
@Component("ElasticConfig")
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticsearchConfig {
// Elasticsearch stuff
private String url;
private String user;
…
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
@Autowired
private ElasticsearchConfig config;
url = config.getUrl();
Spring MicroProfile
Fault Tolerance
A B
Fault Tolerance
import org.eclipse.microprofile.faulttolerance.Fallback;
import org.eclipse.microprofile.faulttolerance.Retry;
import org.eclipse.microprofile.faulttolerance.Timeout;
@Timeout(value = 2, unit = ChronoUnit.SECONDS)
@Retry(maxRetries = 2, maxDuration = 2000)
@CircuitBreaker
@Fallback(fallbackMethod = "fallbackInventory")
@Asynchronous
@GET
public CompletionStage<Item> getInventory() {
….
}
public CompletionStage<Item> fallbackInventory() {
//Returns a default fallback
return fallbackItem;
}
@Service
public class AppService {
@HystrixCommand(fallbackMethod = "fallback")
public List<Item> getInventory() {
return items;
}
public List<Item> fallback() {
//Returns a default fallback
return fallbackitemslist;
}
}
import
org.springframework.cloud.client.circuitbreaker.En
ableCircuitBreaker
@SpringBootApplication
@RestController
@EnableCircuitBreaker
public class Application {
...
}
Spring MicroProfile
MicroProfile Fault Tolerance
A B
@Fallback(fallbackMethod = "fallbackForGet")
public Properties get(String hostname) throws
IOException {
return invUtils.getProperties(hostname);
}
Secure Microservices
A B
© 2018 IBM Corporation
Security: Consuming Json Web Tokens
@DeclareRoles({"Admin", "User"})
@RequestScoped@Path("/orders")
public class OrderService {
@Inject private JsonWebToken jwt;
public Response getOrders() throws Exception {
final String customerId = jwt.getName();
if (customerId == null) {
return “BAD_REQUEST”
}
OrderDAOImpl ordersRepo = new OrderDAOImpl();
final List<Order> orders =
ordersRepo.findByCustomerIdOrderByDateDesc(customerId);
return Response.ok(orders).build();
}
@Configuration
@EnableWebSecurity
@EnableREsourceServer
public class OAuth2ResourceServerConfig extends
ResourceServerConfigurerAdapter {
@Autowired
Private JWTConfig securityConfig;
……….
……….
}
Spring
MicroProfile
MicroProfile JWT
A B
@GET
@RolesAllowed({ "admin", "user" })
@Path("{hostname}")
@Produces(MediaType.APPLICATION_JSON)
public Response getPropertiesForHost(@PathParam("hostname") String hostname,
@Context HttpHeaders httpHeaders) {…}
Handling 100s of collaborating services
requires a strong operations focus
Health Checks
MP Health
Custom health implementation
/health/ready
@Readiness
public class HealthEndpoint
implements ReadinessHealthCheck {
@Override
public HealthCheckResponse
call() {…}
}
/health/live
@Liveness
public class LivenessHealthEndpoint
implements HealthCheck {
@Override
public HealthCheckResponse
call() {…}
}
SpringBoot Actuator
/health – provides us basic health info.
Custom health implementation
@Component
public class HealthCheck implements
HealthIndicator {
@Override
public Health health() {
int errorCode = check(); //
perform some specific health check
if (errorCode != 0) {
return Health.down()
.withDetail("Error
Code", errorCode).build();
}
return Health.up().build();
}
public int check() {
// Our logic to check health
return 0;
}
}
Spring MicroProfile
Metrics
MP Metrics - /metrics endpoint
import
org.eclipse.microprofile.metrics.annotation.Counte
d;
import
org.eclipse.microprofile.metrics.annotation.Metere
d;
import
org.eclipse.microprofile.metrics.annotation.Timed;
@Timed(name = "Inventory.timer", absolute = true,
displayName="Inventory Timer", description =
"Time taken by the Inventory", reusable=true)
@Counted(name="Inventory", displayName="Inventory
Call count", description="Number of times the
Inventory call happened.", monotonic=true,
reusable=true)
@Metered(name="InventoryMeter",
displayName="Inventory Call Frequency",
description="Rate of the calls made to Inventory",
reusable=true)
// Get all rows from database
public List<Item> findAll(){ }
Spring Actuator - /metrics endpoint
Custom Metrics implementation
@Service
public class LoginServiceImpl {
private final CounterService
counterService;
public List<Item> findAll (CounterService
counterService) {
this.counterService = counterService;
if(list.size()>1)
counterService.increment("counter.list.valid
");
else
counterService.increment("counter.list.invalid
");
……………..
………………
……………….
}
Spring MicroProfile
Distributed Tracing
MP OpenTracing
Configuring this features allows us to generate traces for the application
Custom Trace Implementation
import org.eclipse.microprofile.opentracing.Traced;
import io.opentracing.ActiveSpan;
import io.opentracing.Tracer;
@Traced(value = true, operationName ="getCatalog.list")
public List<Item> getInventory() {
try (ActiveSpan childSpan = tracer.buildSpan("Grabbing
messages from Messaging System").startActive()) { }
}
Spring Cloud Sleuth
If the Spring cloud sleuth is configured on the class path, the trace information
will get generated automatically.
Spring
MicroProfile
Our Perspectives
• Developers should be free to choose
what they prefer
• Enterprise should provide developers
with platforms that enable innovation and
flexibility and are enterprise and
production ready
• Liberty supports both MicroProfile/EE
and Spring
• Fast, small, reliable runtime
• Optimized for containers and cloud
• True liberty for microservice developers
and administrators
• Spring is popular
• MicroProfile and Jakarta EE are evolving
rapidly (and gaining momentum) as
community-driven and standards-based
efforts for developing microservices and
cloud-native applications in enterprise
Java
• Both Spring and MicroProfile provide
facilities for developers to build next-
generation applications for cloud
• Share similarities
• There are differences too (and
sometimes, significant)
• Lightweight runtimes for Java/Jakarta EE
are readily available nowadays
Spring Impl MicroProfile Impl
APIs Open Source
Driven by Pivotal
Spring way of things
Open Source
Driven by Community
Open standards
Behaviors in accordance
specifications
Line
s of
Cod
e
More code
Do what you want/need with
code (and configuration)
Less code
Customize server configuration
Libr
arie
s/De
pen
den
cies
Find, mix and match what you
like
Manage your own dependencies
Runtime provides what is needed
per specifications
Appl
icati
on
Pac
kagi
ng
Fat JARs Thin WAR
Note: Liberty has optimized
support for Spring Boot apps in
containers
References
● https://www.ibm.com/blogs/bluemix/2018/09/migrate-java-microservices-from-spring-to-
microprofile-p1/
● https://microprofile.io
○ https://projects.eclipse.org/projects/technology.microprofile
○ https://microprofile.io/projects/
○ https://wiki.eclipse.org/MicroProfile/Implementation
● https://openliberty.io
○ https://openliberty.io/guides/
○ https://openliberty.io/downloads/
○ https://github.com/OpenLiberty/open-liberty
Thank You!

Contenu connexe

Tendances

Metadata Extraction and Content Transformation
Metadata Extraction and Content TransformationMetadata Extraction and Content Transformation
Metadata Extraction and Content TransformationAlfresco Software
 
PLAT-13 Metadata Extraction and Transformation
PLAT-13 Metadata Extraction and TransformationPLAT-13 Metadata Extraction and Transformation
PLAT-13 Metadata Extraction and TransformationAlfresco Software
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSPGeethu Mohan
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
Share point review qustions
Share point review qustionsShare point review qustions
Share point review qustionsthan sare
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCJohn Lewis
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsBG Java EE Course
 
A Complete Tour of JSF 2
A Complete Tour of JSF 2A Complete Tour of JSF 2
A Complete Tour of JSF 2Jim Driscoll
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVCJohn Lewis
 

Tendances (19)

Metadata Extraction and Content Transformation
Metadata Extraction and Content TransformationMetadata Extraction and Content Transformation
Metadata Extraction and Content Transformation
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
PLAT-13 Metadata Extraction and Transformation
PLAT-13 Metadata Extraction and TransformationPLAT-13 Metadata Extraction and Transformation
PLAT-13 Metadata Extraction and Transformation
 
Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
 
Spring tutorial
Spring tutorialSpring tutorial
Spring tutorial
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
Share point review qustions
Share point review qustionsShare point review qustions
Share point review qustions
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Struts N E W
Struts N E WStruts N E W
Struts N E W
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
A Complete Tour of JSF 2
A Complete Tour of JSF 2A Complete Tour of JSF 2
A Complete Tour of JSF 2
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVC
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
Jsf intro
Jsf introJsf intro
Jsf intro
 

Similaire à Emily Jiang, Java Champion discusses cloud-native microservices

Master a Cloud Native Standard - MicroProfile.pptx
Master a Cloud Native Standard - MicroProfile.pptxMaster a Cloud Native Standard - MicroProfile.pptx
Master a Cloud Native Standard - MicroProfile.pptxEmilyJiang23
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web servicesnbuddharaju
 
Cloud nativeworkshop
Cloud nativeworkshopCloud nativeworkshop
Cloud nativeworkshopEmily Jiang
 
Android application architecture
Android application architectureAndroid application architecture
Android application architectureRomain Rochegude
 
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
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 
Implement Service Broker with Spring Boot #cf_tokyo
Implement Service Broker with Spring Boot #cf_tokyoImplement Service Broker with Spring Boot #cf_tokyo
Implement Service Broker with Spring Boot #cf_tokyoToshiaki Maki
 
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
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code lessAnton Novikau
 
Graphql + Symfony | Александр Демченко | CODEiD
Graphql + Symfony | Александр Демченко | CODEiDGraphql + Symfony | Александр Демченко | CODEiD
Graphql + Symfony | Александр Демченко | CODEiDCODEiD PHP Community
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsHassan Abid
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss Andres Almiray
 
iOS Swift application architecture
iOS Swift application architectureiOS Swift application architecture
iOS Swift application architectureRomain Rochegude
 

Similaire à Emily Jiang, Java Champion discusses cloud-native microservices (20)

Master a Cloud Native Standard - MicroProfile.pptx
Master a Cloud Native Standard - MicroProfile.pptxMaster a Cloud Native Standard - MicroProfile.pptx
Master a Cloud Native Standard - MicroProfile.pptx
 
RESTing with JAX-RS
RESTing with JAX-RSRESTing with JAX-RS
RESTing with JAX-RS
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
Cloud nativeworkshop
Cloud nativeworkshopCloud nativeworkshop
Cloud nativeworkshop
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Android application architecture
Android application architectureAndroid application architecture
Android application architecture
 
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)
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
Arquitecturas de microservicios - Medianet Software
Arquitecturas de microservicios   -  Medianet SoftwareArquitecturas de microservicios   -  Medianet Software
Arquitecturas de microservicios - Medianet Software
 
Implement Service Broker with Spring Boot #cf_tokyo
Implement Service Broker with Spring Boot #cf_tokyoImplement Service Broker with Spring Boot #cf_tokyo
Implement Service Broker with Spring Boot #cf_tokyo
 
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
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code less
 
Symfony + GraphQL
Symfony + GraphQLSymfony + GraphQL
Symfony + GraphQL
 
Graphql + Symfony | Александр Демченко | CODEiD
Graphql + Symfony | Александр Демченко | CODEiDGraphql + Symfony | Александр Демченко | CODEiD
Graphql + Symfony | Александр Демченко | CODEiD
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
 
Spring boot
Spring boot Spring boot
Spring boot
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss
 
Bpstudy20101221
Bpstudy20101221Bpstudy20101221
Bpstudy20101221
 
iOS Swift application architecture
iOS Swift application architectureiOS Swift application architecture
iOS Swift application architecture
 

Plus de Emily Jiang

Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020Emily Jiang
 
Reactive microserviceinaction
Reactive microserviceinactionReactive microserviceinaction
Reactive microserviceinactionEmily Jiang
 
Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020Emily Jiang
 
Reactive microserviceinaction@devnexus
Reactive microserviceinaction@devnexusReactive microserviceinaction@devnexus
Reactive microserviceinaction@devnexusEmily Jiang
 
Live Coding 12 Factor App
Live Coding 12 Factor AppLive Coding 12 Factor App
Live Coding 12 Factor AppEmily Jiang
 
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 nexusEmily Jiang
 
Cloud native programming model comparison
Cloud native programming model comparisonCloud native programming model comparison
Cloud native programming model comparisonEmily Jiang
 
Micro profile and istio
Micro profile and istioMicro profile and istio
Micro profile and istioEmily Jiang
 
Building cloud native microservices
Building cloud native microservicesBuilding cloud native microservices
Building cloud native microservicesEmily Jiang
 
The new and smart way to build microservices - Eclipse MicroProfile
The new and smart way to build microservices - Eclipse MicroProfileThe new and smart way to build microservices - Eclipse MicroProfile
The new and smart way to build microservices - Eclipse MicroProfileEmily Jiang
 
Build12 factorappusingmp
Build12 factorappusingmpBuild12 factorappusingmp
Build12 factorappusingmpEmily Jiang
 
New and smart way to develop microservice for istio with micro profile
New and smart way to develop microservice for istio with micro profileNew and smart way to develop microservice for istio with micro profile
New and smart way to develop microservice for istio with micro profileEmily Jiang
 

Plus de Emily Jiang (12)

Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020
 
Reactive microserviceinaction
Reactive microserviceinactionReactive microserviceinaction
Reactive microserviceinaction
 
Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020
 
Reactive microserviceinaction@devnexus
Reactive microserviceinaction@devnexusReactive microserviceinaction@devnexus
Reactive microserviceinaction@devnexus
 
Live Coding 12 Factor App
Live Coding 12 Factor AppLive Coding 12 Factor App
Live Coding 12 Factor App
 
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
 
Cloud native programming model comparison
Cloud native programming model comparisonCloud native programming model comparison
Cloud native programming model comparison
 
Micro profile and istio
Micro profile and istioMicro profile and istio
Micro profile and istio
 
Building cloud native microservices
Building cloud native microservicesBuilding cloud native microservices
Building cloud native microservices
 
The new and smart way to build microservices - Eclipse MicroProfile
The new and smart way to build microservices - Eclipse MicroProfileThe new and smart way to build microservices - Eclipse MicroProfile
The new and smart way to build microservices - Eclipse MicroProfile
 
Build12 factorappusingmp
Build12 factorappusingmpBuild12 factorappusingmp
Build12 factorappusingmp
 
New and smart way to develop microservice for istio with micro profile
New and smart way to develop microservice for istio with micro profileNew and smart way to develop microservice for istio with micro profile
New and smart way to develop microservice for istio with micro profile
 

Dernier

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
(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
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
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
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 

Dernier (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
(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...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
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...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 

Emily Jiang, Java Champion discusses cloud-native microservices

  • 1. Emily Jiang, Java Champion Senior Technical Staff Member, IBM Liberty Microservice Architect, Advocate Senior Lead for MicroProfile and CDI @emilyfhjiang Creating a cloud-native microservice – which programming mode should I use?
  • 2.
  • 3.
  • 4. Characteristics Specs, APIs, TCKs Community Driven Lightweight, Iterative Processes No Reference Impls!
  • 5. MicroProfile 1.0 (Fall 2016) jaxrs-2.0 cdi-1.2 jsonp-1.0 MicroProfile 1.1 (August 2017) microProfile-1.0 mpConfig-1.0 MicroProfile 1.2 (Sept 2017) microProfile-1.1 mpConfig-1.1 mpFaultTolerance-1.0 mpHealth-1.0 mpMetrics-1.0 mpJwt-1.0 2017 2018 MicroProfile 1.3 (Dec 2017) MicroProfile 1.2 mpConfig-1.2 mpMetrics-1.1 mpOpenApi-1.0 mpOpenTracing-1.0 mpRestClient-1.0 MicroProfile 1.4 (June 2018) MicroProfile 1.3 mpConfig-1.3 mpFaultTolerance-1.1 mpJwt-1.1 mpOpenTracing-1.1 mpRestClient-1.1 2019 MicroProfile 2.0.1 (July 2018) MicroProfile 1.4 jaxrs-2.1 // Java EE 8 cdi-2.0 // Java EE 8 jsonp-1.1 // Java EE 8 jsonb-1.0 // Java EE 8 MicroProfile 2.1 (Oct 2018) MicroProfile 2.0 mpOpenTracing-1.2 MicroProfile 2.2 (Feb 2019) Fault Tolerance 2.0 OpenAPI 1.1 OpenTracing 1.3 Rest Client 1.2 Jan 19.0.0.8 19.0.0.7 19.0.0.9 MicroProfile 3.0 (June 2019) Metrics 2.0 Health Check 2.0 Rest Client 1.3
  • 6. CDI 2.0 Latest release JAX-RS 2.1 JSON-P 1.1 MicroProfile 3.0 JSON-B 1.0 Fault Tolerance 2.0 Metrics 2.0 JWT Propagation 1.1 Health Check 2.0 Open Tracing 1.3 Open API 1.1 Rest Client 1.3 Config 1.3 20+ Component Releases! 9 Platform Releases! MicroProfile 3.0 Reactive Streams Operators Reactive Messaging Context Propagation Standalone releases
  • 7. Open specifications Wide vendor support REST services OpenAPI support Security Fault Tolerance Configuration Metrics Health Open Tracing https://wiki.eclipse.org/MicroProfile/Implementation Implementations
  • 8. Spring MicroProfile Getting started Starter https://start.spring.io/ https://start.microprofile.io/ REST REST Service Spring MVC JAX-RS Dependency Injection Spring IoC & DI CDI API Documentation Spring REST Docs MP Open API REST Client Spring MVC Feign MP REST Client JSON Binding/Processing Bring Your Own Llibrary Jackson, JSON-B JSON-B JSON-P Reactive Reactive Spring Reactor Use Kafka APIs to connect with Kafka MicroProfile Reactive Streams Operator, RxJava MicroProfile Reactive Messaging Handling 100s of Services Configuration Spring Boot Config Spring Cloud Config MP Config Fault Tolerance Netflix Hystrix MP Fault Tolerance Security Spring Security Spring Cloud Security EE Security MP JWT Propagation Operation Focus Health Checks Spring Boot Actuator MP Health Check Metrics Spring Boot Actuator MP Metrics Distributed Tracing Spring Cloud Sleuth MP Open Tracing Capabilities
  • 10. There’s a good chance you’ll use REST APIs
  • 12. REST Services @ApplicationPath("/rest") public class CatalogApplication extends Application { } @Path("/items") @Produces(MediaType.APPLICATION_J SON) public class CatalogService {..} @GET public List<Item> getInventory() {…} @GET @Path("{id}") public Response getById(@PathParam("id") long id) {…} @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args);} } @RestController public class CatalogController {..} @RequestMapping(value = "/items", method = RequestMethod.GET) @ResponseBody List<Item> getInventory() {..} @RequestMapping(value = "/items/{id}", method = RequestMethod.GET) ResponseEntity<?> getById(@PathVariable long id) {…} Spring MicroProfile
  • 13. JAX-RS in MicroProfile B @ApplicationPath("System") public class SystemApplication extends Application {} @Path("properties") public class PropertiesResource { @GET @Produces(MediaType.APPLICATION_JSON) public JsonObject getProperties() {…} }
  • 15. Dependency Injection @ApplicationPath("/rest") public class JaxrsApplication extends Application { @Inject private InventoryRefreshTask refreshTask; @ApplicationScoped public class InventoryRefreshTask { … } @SpringBootApplication public class Application { @Autowired private InventoryRefreshTask refreshTask; Spring MicroProfile B
  • 16. CDI for MicroProfile A public class InventoryManager { @Inject private SystemClient systemClient; … }
  • 18. © 2018 IBM Corporation Document APIs in Spring 1 8 1. Define the dependencies <dependency> <groupId>org.springframework.restdocs</groupId> <artifactId>spring-restdocs-mockmvc</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.restdocs</groupId> <artifactId>spring-restdocs-core</artifactId> <scope>test</scope> </dependency> 2. Define your Rest service -------------------- @RestController public class CatalogController { @RequestMapping("/") public @ResponseBody String index() { return "Greetings from Catalog Service !"; } } ----------------- 3. Define all necessary test classes @RunWith(SpringRunner.class) @SpringBootTest(classes = CatalogController.class) @WebAppConfiguration public class CatalogControllerTest { @Rule public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets"); private MockMvc mockMvc; @Autowired private WebApplicationContext context; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(context) .apply(documentationConfiguration(restDocumentation)) .build(); } 4. Use alwaysDo(), responseFileds(), requestPayload(), links(), fieldWithPath(), requestParameters(), pathParameters() to document @Test public void crudDeleteExample() throws Exception { this.mockMvc.perform(delete("/crud/{id}", 10)).andExpect(status().isOk()) .andDo(document("crud-delete-example", pathParameters( parameterWithName("id").description("The id of the input to delete") ))); }
  • 19. MicroProfile OpenAPI A B openapi: 3.0.0 info: title: Inventory App description: App for storing JVM system properties of various hosts. license: name: Eclipse Public License - v 1.0 url: https://www.eclipse.org/legal/epl-v10.html version: "1.0" servers: - url: http://localhost:{port} description: Simple Open Liberty. variables: port: description: Server HTTP port. default: "9080" paths: /inventory/systems: get: summary: List inventory contents. description: Returns the currently stored host:properties pairs in the inventory. operationId: listContents responses: 200: description: host:properties pairs stored in the inventory. content: application/json: schema: $ref: '#/components/schemas/InventoryList’ …. http://localhost:9080/openapi/ui @GET @Produces(MediaType.APPLICATION_JSON) @APIResponse( responseCode = "200", description = "host:properties pairs stored in the inventory.", content = @Content( mediaType = "application/json", schema = @Schema( type = SchemaType.OBJECT, implementation = InventoryList.class))) @Operation( summary = "List inventory contents.", description = "Returns the stored host:properties pairs.") public InventoryList listContents() { return manager.list(); }
  • 21. REST Clients 2 1 @Dependent @RegisterRestClient @RegisterProvider(InventoryResponseExceptionMapper.class) // Optional public interface InventoryServiceClient { @GET @Produces(MediaType.APPLICATION_JSON) List<Item> getAllItems() throws UnknownUrlException, ServiceNotReadyException; } @Inject @RestClient private InventoryServiceClient invClient; final List<Item> allItems = invClient.getAllItems(); @FeignClient(name="inventory-service", url="${inventoryService.url}") public interface InventoryServiceClient { @RequestMapping(method=RequestMethod.GET, value="/micro/inventory", produces={MediaType.APPLICATION_JSON_VALUE}) List<Item> getAllItems(); } @EnableFeignClients public class Application { @Autowired private InventoryServiceClient invClient; final List<Item> allItems = invClient.getAllItems(); Spring MicroProfile
  • 22. MicroProfile REST Client BA @Inject @RestClient private SystemClient defaultRestClient; @Dependent @RegisterRestClient @RegisterProvider(UnknownUrlExceptionMapper.class) @Path("/properties") public interface SystemClient { @GET @Produces(MediaType.APPLICATION_JSON) public Properties getProperties() throws UnknownUrlException, ProcessingException; } io.openliberty.guides.inventory.client.SystemClient/mp-rest/url=http://localhost:9080/system
  • 24. JSON Binding/Processing import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; Jsonb jsonb = JsonbBuilder.create(); String result = jsonb.toJson(artists); import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; final ObjectMapper objMapper = new ObjectMapper(); jsonString = objMapper.writeValueAsString(item); // or import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; Jsonb jsonb = JsonbBuilder.create(); String result = jsonb.toJson(artists); MicroProfile Spring
  • 25. JSON-B & JSON-P in MicroProfile A B ... @GET @Produces(MediaType.APPLICATION_JSON) public InventoryList listContents() { return manager.list(); } public class InventoryList { private List<SystemData> systems; public InventoryList(List<SystemData> systems) { this.systems = systems; } public List<SystemData> getSystems() { return systems; } public int getTotal() { return systems.size(); } }
  • 26. Reactive MicroProfile Reactive Stream Operators to work with Reactive Streams Can also use RxJava MicroProfile Reactive Messaging Spring MicroProfile Use Spring Reactor Directly use Kafka APIs or Spring boot annotations to interact with Kafka streams @KafkaListener(topics = "users", groupId = "group_id") public void consume(String message){ … } @Autowired private KafkaTemplate<String,String> kafkaTemplate; public void sendMessage(String message){ logger.info(String.format("$$ -> Producing message --> %s",message)); this.kafkaTemplate.send(TOPIC,message); }
  • 27. Handling 100s of Services
  • 29. Configuration 2 9 # Elasticsearch elasticsearch_url=http://es-catalog- elasticsearch:9200 elasticsearch_index=micro elasticsearch_doc_type=items ===================== Config config = ConfigProvider.getConfig(); private String url = config.getValue("elasticsearch_url", String.class); ===================== @Inject @ConfigProperty(name=“elasticsearch_url”) String url; # Elasticsearch elasticsearch: url: http://localhost:9200 user: password: index: micro doc_type: items ===================== @Component("ElasticConfig") @ConfigurationProperties(prefix = "elasticsearch") public class ElasticsearchConfig { // Elasticsearch stuff private String url; private String user; … public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } @Autowired private ElasticsearchConfig config; url = config.getUrl(); Spring MicroProfile
  • 31. Fault Tolerance import org.eclipse.microprofile.faulttolerance.Fallback; import org.eclipse.microprofile.faulttolerance.Retry; import org.eclipse.microprofile.faulttolerance.Timeout; @Timeout(value = 2, unit = ChronoUnit.SECONDS) @Retry(maxRetries = 2, maxDuration = 2000) @CircuitBreaker @Fallback(fallbackMethod = "fallbackInventory") @Asynchronous @GET public CompletionStage<Item> getInventory() { …. } public CompletionStage<Item> fallbackInventory() { //Returns a default fallback return fallbackItem; } @Service public class AppService { @HystrixCommand(fallbackMethod = "fallback") public List<Item> getInventory() { return items; } public List<Item> fallback() { //Returns a default fallback return fallbackitemslist; } } import org.springframework.cloud.client.circuitbreaker.En ableCircuitBreaker @SpringBootApplication @RestController @EnableCircuitBreaker public class Application { ... } Spring MicroProfile
  • 32. MicroProfile Fault Tolerance A B @Fallback(fallbackMethod = "fallbackForGet") public Properties get(String hostname) throws IOException { return invUtils.getProperties(hostname); }
  • 34. © 2018 IBM Corporation Security: Consuming Json Web Tokens @DeclareRoles({"Admin", "User"}) @RequestScoped@Path("/orders") public class OrderService { @Inject private JsonWebToken jwt; public Response getOrders() throws Exception { final String customerId = jwt.getName(); if (customerId == null) { return “BAD_REQUEST” } OrderDAOImpl ordersRepo = new OrderDAOImpl(); final List<Order> orders = ordersRepo.findByCustomerIdOrderByDateDesc(customerId); return Response.ok(orders).build(); } @Configuration @EnableWebSecurity @EnableREsourceServer public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter { @Autowired Private JWTConfig securityConfig; ………. ………. } Spring MicroProfile
  • 35. MicroProfile JWT A B @GET @RolesAllowed({ "admin", "user" }) @Path("{hostname}") @Produces(MediaType.APPLICATION_JSON) public Response getPropertiesForHost(@PathParam("hostname") String hostname, @Context HttpHeaders httpHeaders) {…}
  • 36. Handling 100s of collaborating services requires a strong operations focus
  • 37. Health Checks MP Health Custom health implementation /health/ready @Readiness public class HealthEndpoint implements ReadinessHealthCheck { @Override public HealthCheckResponse call() {…} } /health/live @Liveness public class LivenessHealthEndpoint implements HealthCheck { @Override public HealthCheckResponse call() {…} } SpringBoot Actuator /health – provides us basic health info. Custom health implementation @Component public class HealthCheck implements HealthIndicator { @Override public Health health() { int errorCode = check(); // perform some specific health check if (errorCode != 0) { return Health.down() .withDetail("Error Code", errorCode).build(); } return Health.up().build(); } public int check() { // Our logic to check health return 0; } } Spring MicroProfile
  • 38. Metrics MP Metrics - /metrics endpoint import org.eclipse.microprofile.metrics.annotation.Counte d; import org.eclipse.microprofile.metrics.annotation.Metere d; import org.eclipse.microprofile.metrics.annotation.Timed; @Timed(name = "Inventory.timer", absolute = true, displayName="Inventory Timer", description = "Time taken by the Inventory", reusable=true) @Counted(name="Inventory", displayName="Inventory Call count", description="Number of times the Inventory call happened.", monotonic=true, reusable=true) @Metered(name="InventoryMeter", displayName="Inventory Call Frequency", description="Rate of the calls made to Inventory", reusable=true) // Get all rows from database public List<Item> findAll(){ } Spring Actuator - /metrics endpoint Custom Metrics implementation @Service public class LoginServiceImpl { private final CounterService counterService; public List<Item> findAll (CounterService counterService) { this.counterService = counterService; if(list.size()>1) counterService.increment("counter.list.valid "); else counterService.increment("counter.list.invalid "); …………….. ……………… ………………. } Spring MicroProfile
  • 39. Distributed Tracing MP OpenTracing Configuring this features allows us to generate traces for the application Custom Trace Implementation import org.eclipse.microprofile.opentracing.Traced; import io.opentracing.ActiveSpan; import io.opentracing.Tracer; @Traced(value = true, operationName ="getCatalog.list") public List<Item> getInventory() { try (ActiveSpan childSpan = tracer.buildSpan("Grabbing messages from Messaging System").startActive()) { } } Spring Cloud Sleuth If the Spring cloud sleuth is configured on the class path, the trace information will get generated automatically. Spring MicroProfile
  • 40. Our Perspectives • Developers should be free to choose what they prefer • Enterprise should provide developers with platforms that enable innovation and flexibility and are enterprise and production ready • Liberty supports both MicroProfile/EE and Spring • Fast, small, reliable runtime • Optimized for containers and cloud • True liberty for microservice developers and administrators • Spring is popular • MicroProfile and Jakarta EE are evolving rapidly (and gaining momentum) as community-driven and standards-based efforts for developing microservices and cloud-native applications in enterprise Java • Both Spring and MicroProfile provide facilities for developers to build next- generation applications for cloud • Share similarities • There are differences too (and sometimes, significant) • Lightweight runtimes for Java/Jakarta EE are readily available nowadays
  • 41. Spring Impl MicroProfile Impl APIs Open Source Driven by Pivotal Spring way of things Open Source Driven by Community Open standards Behaviors in accordance specifications Line s of Cod e More code Do what you want/need with code (and configuration) Less code Customize server configuration Libr arie s/De pen den cies Find, mix and match what you like Manage your own dependencies Runtime provides what is needed per specifications Appl icati on Pac kagi ng Fat JARs Thin WAR Note: Liberty has optimized support for Spring Boot apps in containers
  • 42. References ● https://www.ibm.com/blogs/bluemix/2018/09/migrate-java-microservices-from-spring-to- microprofile-p1/ ● https://microprofile.io ○ https://projects.eclipse.org/projects/technology.microprofile ○ https://microprofile.io/projects/ ○ https://wiki.eclipse.org/MicroProfile/Implementation ● https://openliberty.io ○ https://openliberty.io/guides/ ○ https://openliberty.io/downloads/ ○ https://github.com/OpenLiberty/open-liberty