tdc2016sp - construindo microserviços usando spring cloud

Post on 14-Jan-2017

201 Views

Category:

Education

3 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Construindo Microservices com

Spring Cloud

Arquitetura Java

Claudio Eduardode Oliveira

AboutMe Acionistas

Claudio Eduardo de OliveiraJava Developer @ ADTsys

Bacharel em Ciência da Computação

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

Entusiasta Docker / Spring

SOBREADTSYS

Eat your

own

Dog Food

Agenda

Motivação

Microservices

Spring Boot + Spring Cloud

Portifólio de projetos

o Spring Cloud Config

o Spring Cloud Eureka

o Spring Cloud Bus

o Spring Cloud Hystrix

o Spring Cloud Zuul

MOTIVAÇÃO

http://www.infoworld.com/article/3075880/application-development/microservice-architecture-is-agile-software-architecture.html

MICROSERVICES

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

MICROSERVICESVANTAGENS

- Desacoplamento

- Agilidade na entrega de Valor

- Deploy independente

- Diversidade tecnológica

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

MICROSERVICESDESVANTAGENS

- Complexidade Operacional

- Comunicação

- Consistência Eventual

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

MICROSERVICES

- Configurações Centralizadas

- Service Registry / Service Discovery

- Circuit Breaker

- API Proxy

NuvemHíbrida

NuvemHíbrida

Spring Cloud Netflix OSS

+

NuvemHíbrida

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 BusSetup

info: 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

o clientes se registram no servidor

o servidor lista os clienteso clientes conhecem são

reconhecidos por outros clientes

spring cloud eurekaService DiscoveryDesafios

o # de chamadas a microserviceso configuração manual impraticávelo # de instâncias de serviçoso 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 ClientSetupinfo: 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

o API internas “expostas”o segurançao CORSo Roteamentoo Versionamentoo Cacheo # excessivo de chamadas remotas

spring cloud zuulAPI ProxySpring Cloud Zuul

o filtros (pre/pos)o roteamento para serviçoso versionamento de APIso CORSo 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 ZuulSetupinfo: 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/

top related