TDC 2016 - Arquitetura Java - Spring Cloud

Post on 13-Jan-2017

190 views 2 download

Transcript of TDC 2016 - Arquitetura Java - Spring Cloud

Construindo Microservices com

Spring Cloud

Arquitetura Java

Claudio Eduardode Oliveira

About meClaudio Eduardo de Oliveira

Java Developer @ ADTsys

Bacharel em Ciência da Computação

Cursando MBA em Arquitetura de Soluções em Tecnologia (DeVry/Metrocamp)

Entusiasta Docker / SpringContatos:

Email: claudioed.oliveira@gmail.comLinkedin: https://br.linkedin.com/in/claudioedoliveiraTwitter: @claudioedBlog: www.claudioliveira.com

Eat your

own

Dog Food

AgendaMotivação

Microservices

Spring Boot + Spring Cloud

Portifólio de projetos

Spring Cloud Config

Spring Cloud Eureka

Spring Cloud Bus

Spring Cloud Hystrix

Spring Cloud Zuul

The term "Microservice Architecture" has sprung up over the last few years to describe

a particular way of designing software applications as suites of independently deployable services. While there is no

precise definition of this architectural style, there are certain common characteristics around organization around business

capability, automated deployment, intelligence in the endpoints, and

decentralized control of languages and data

http://martinfowler.com/articles/microservices.html

microservices

- Desacoplamento

- Agilidade na entrega de

Valor- Deploy independente

- Diversidade tecnológica

Vantagens

http://martinfowler.com/articles/microservice-trade-offs.html

microservices

- Complexidade Operacional

- Comunicação

- Consistência Eventual

Desvantagens

http://martinfowler.com/articles/microservice-trade-offs.html

microservices

microservices

- Configurações Centralizadas

- Service Registry / Service

Discovery

- Circuit Breaker

- API Proxy

Spring Cloud Netflix OSS

+

Advice

spring boot

spring boot

- criação de aplicações standalone

spring

- NO xml

- configuração automática

- métricas e health checks

- tomcat, jetty ou undertow embed

spring bootfeatures

spring cloud

spring cloud

=

spring boot+

steroids

spring cloud

- spring cloud config- spring cloud netflix- spring cloud security

- spring cloud bus- spring cloud consul

- spring cloud sleuth

- spring cloud stream

- spring cloud zookeeper

- ...

portifólio

http://projects.spring.io/spring-cloud/

spring cloud config

- Configurações Centralizadas- Service Registry / Service

Discovery

- Circuit Breaker

- API Proxy

- HTTP resource based API

- encrypt / Decrypt

- integração Spring Boot

@EnableConfigServer

- suporte múltiplos ambiente

(dev, qa, prod)

- arquivos (github / filesystem)

spring cloud config

- spring cloud server

- spring cloud client

spring cloud config

spring cloud configConfig ServerDependência

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId></dependency>

spring cloud configConfig ServerSetup/*** @author Claudio E. de Oliveira.*/@SpringCloudApplication@EnableConfigServerpublic class ConfigApplication {

public static void main(String[] args) { SpringApplication.run(ConfigApplication.class, args); } }

spring cloud configConfig ServerSetup (bootstrap.yml)spring: application: name: configserver

spring cloud config

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId></dependency>

Config ClientDependência

spring cloud configConfig ClientSetup (bootstrap.yml)spring: profiles: default application: name: predictors cloud: config: uri: http://configserver:8001/

server: port: 7003

Cloud Busspring cloud bus

- Push de configurações

- RabbitMQ

spring cloud busConfig Client BusFuncionamento

spring cloud busCloud BusDependência

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId></dependency>

spring cloud busConfig Client BusSetupinfo: component: Predictor MicroService

spring: rabbitmq: host: localhost port: 5672 username: guest password: guest

spring cloud busConfig Client BusExemplo

@Service@RefreshScopepublic class ParticipantService {

@Autowired private RestTemplate restTemplate;

@Value("${services.user.info}") private String url;

}

spring cloud busConfig Client BusExemplo

services: user: info: http://USERS/ event: info: http://EVENTS/

spring cloud eureka

- Configurações Centralizadas

- Service Registry / Service

Discovery- Circuit Breaker

- API Proxy

spring cloud eurekaService DiscoveryConceito

● clientes se registram no servidor

● servidor lista os clientes● clientes conhecem são

reconhecidos por outros clientes

spring cloud eurekaService DiscoveryDesafios

● # de chamadas a microservices● configuração manual

impraticável● # de instâncias de serviços● resolver dependências em

runtime

- “lookup” de serviços

- clientes enviam heartbeats

- remoção de clientes não

funcionais

- testado em produção pelo

Netflix

spring cloud eureka

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId></dependency>

spring cloud eurekaEureka ServerDependência

spring cloud eurekaEureka ServerSetup@SpringBootApplication@EnableEurekaServer@EnableDiscoveryClientpublic class DiscoveryApplication{

public static void main(String[] args) { SpringApplication.run(DiscoveryApplication.class, args); } }

spring cloud eurekaEureka ServerExemplo

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId></dependency>

spring cloud eurekaEureka ClientDependência

spring cloud eurekaEureka ClientSetup

info: component: Ranking MicroService

server: port: 7002

eureka: client: serviceUrl: defaultZone: http://discovery:8761/eureka/

spring cloud eurekaEureka ClientSetup

@SpringCloudApplicationpublic class RankingApplication {

public static void main(String[] args) throws Exception { SpringApplication.run(RankingApplication.class, args); }

}

spring cloud eurekaEureka ClientSetup@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@SpringBootApplication@EnableDiscoveryClient@EnableCircuitBreakerpublic @interface SpringCloudApplication {}

spring cloud hystrix

- Configurações Centralizadas

- Service Registry / Service

Discovery

- Circuit Breaker- API Proxy

Falácias da Computação Distribuída

spring cloud hystrix

1. A rede é confíavel2. A latência é zero3. A largura da banda é infinita4. A rede é segura5. A topologia não se altera6. Existe apenas um administrador7. Custo de transporte é zero8. A rede é homogênea

spring cloud hystrixCascading FailuresProblema

● # número de dependências pode levar ao “cascading failures”

● sistemas distribuídos por padrão tem mais chances de falhar

Circuit BreakerConceito

spring cloud hystrix

● Mesmo comportamento de um circuito elétrico

● “Aberto” falha na operação e a mesma não deve

ser chamada

● “Fechado” funcionamento normal, a operação

pode ser chamada

● “Parcialmente Aberto” pode haver chamada mas

serão auditadas para ver se o problema ainda

persiste

Netflix Hystrixspring cloud hystrix

● provê mecanismo de “fallback”

● “fallbacks” podem ser encadeados (cuidado!!!)

● fácil integração com Spring (via annotations)

● fechamento automático do circuito

spring cloud hystrix

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId></dependency>

Cloud HystrixDependência

spring cloud hystrixCloud HystrixSetup

@SpringCloudApplication@EnableHystrixpublic class PredictorApplication {

public static void main(String[] args) throws Exception { SpringApplication.run(PredictorApplication.class, args); }

}

spring cloud hystrixCloud HystrixExemplo (command)

@Service@RefreshScopepublic class ParticipantService {

@HystrixCommand(fallbackMethod = "getParticipantInCache") public Participant getUserInfo(String participantId){ log.info("[REQUEST-PARTICIPANT-INFO] Request event info "); ResponseEntity<Participant> response = this.restTemplate.getForEntity(this.url + participantId, Participant.class); final Participant participant = response.getBody(); cache.put(participant.getId(),participant); return participant; }

}

spring cloud hystrixCloud HystrixExemplo (fallback)

@Service@RefreshScopepublic class ParticipantService {

public Participant getParticipantInCache(String participantId){ Participant cachedParticipant = cache.getIfPresent(participantId); if(Objects.isNull(cachedParticipant)){ log.error(String.format("[REQUEST-PARTICIPANT-INFO] CACHE - Error on retrieve participant %s information", participantId)); throw new InvalidParticipant(participantId); } return cachedParticipant;}

}

spring cloud hystrix

● microservices sem monitoramento torna-se

impraticável

● hystrix provê dashboards

● @EnableHystrixDashboard

Cloud HystrixMonitoramento

spring cloud zuul

- Configurações Centralizadas

- Service Registry / Service

Discovery

- Circuit Breaker

- API Proxy

spring cloud zuulAPI ProxyProblemas

● API internas “expostas”● segurança● CORS● Roteamento● Versionamento● Cache● # excessivo de chamadas remotas

spring cloud zuulAPI ProxySpring Cloud Zuul

● filtros (pre/pos)● roteamento para serviços● versionamento de APIs● CORS● integração Eureka (service name)

spring cloud zuul

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId></dependency>

Cloud ZuulDependência

spring cloud zuulCloud ZuulSetup

@SpringCloudApplication@Controller@EnableZuulProxypublic class GatewayApplication {

public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }

spring cloud zuulCloud ZuulSetup

info: component: API Gateway (Zull Proxy)

eureka: registryFetchIntervalSeconds: 5 serviceUrl: defaultZone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/

zuul: routes: users: path: /api/v1/users/** serviceId: users

spring cloud zuulCloud ZuulExemplo (client)@SpringCloudApplication@EnableZuulProxypublic class EventApplication {

public static void main(String[] args) throws Exception { SpringApplication.run(EventApplication.class, args); }

}

#tip

email: claudioed.oliveira@gmail.com

linkedin: https://br.linkedin.com/in/claudioedoliveira

twitter: @claudioed

blog: www.claudioliveira.com

github: https://github.com/claudioed

Claudio Eduardo de Oliveira

Referências

http://martinfowler.com/articles/microservices.html

http://microservices.io/

http://microservices.io/patterns/apigateway.html

http://projects.spring.io/spring-boot/

https://cloud.spring.io/spring-cloud-netflix/

http://callistaenterprise.se/blogg/teknik/2015/04/10/building-microservices-with-spring-cloud-and-netflix-oss-part-1/