Spring Cloud Eureka-服务注册、消费、断路

来源:互联网 发布:java中bigdecimal相加 编辑:程序博客网 时间:2024/06/16 00:53

一、服务注册

新建eureka-provider maven项目

1、pom配置

<parent>    <groupId>org.springframework.cloud</groupId>    <artifactId>spring-cloud-starter-parent</artifactId>    <version>Brixton.SR4</version>    <relativePath/> </parent><dependency>  <groupId>org.springframework.cloud</groupId>  <artifactId>spring-cloud-starter-eureka</artifactId></dependency>

2、application.properties

主要配置服务中心的地址,用于注册服务

# 指定应用名称spring.application.name=hello-service# 构建服务中心的地址eureka.client.serviceUrl.defaultZone= http://peer1:1111/eureka/,http://peer2:1112/eureka/

3 、代码

HelloworldApplication:启动服务注册,通过EnableDiscoveryClient注解发现client

package com.tan.self;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;    /**     * Author: Mr.tan     * Date: 2017/9/9     */    @EnableDiscoveryClient    @SpringBootApplication    public class HelloworldApplication {        public static void main(String[] args) {            SpringApplication.run(HelloworldApplication.class, args);        }    }

HelloController:提供一个简单的rest服务,返回数据

package com.tan.self;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cloud.client.ServiceInstance;import org.springframework.cloud.client.discovery.DiscoveryClient;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;/** * Author: Mr.tan * Date: 2017/9/9 */@RestControllerpublic class HelloController {    private final Logger log = LoggerFactory.getLogger(getClass());    @Autowired    private DiscoveryClient client;    @RequestMapping(value = "/hello", method = RequestMethod.GET)    public String index(){        ServiceInstance instance = client.getLocalServiceInstance();        log.info("/hello, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());        return "Hello World !";    }}

4、启动

启动HelloworldApplication,向注册中心注册服务。查看eureka的监控:

这里写图片描述

二、服务消费

服务消费者主要完成两个任务——服务的发现和服务的消费,服务发现的任务是由Eureka客户端完成,而服务消费的任务是由Ribbon完成。

Ribbon是一个基于HTTP和TCP客户端的负载均衡器。它可以在通过客户端中配置ribbonServerList服务端列表去轮询访问以达到负载均衡目的。

当Ribbon和Eureka同时使用时,Ribbon的服务实例清单RibbonServerList会被DiscoveryEnableNIEWServerList重写。

Ribbon将职责交给Eureka来确定服务端是否已经启动。

1、启动多个服务注册

将上文完成的注册中心以jar形式启动

java -jar eureka-provider-1.0-SNAPSHOT.jar --server.port=8081java -jar eureka-provider-1.0-SNAPSHOT.jar --server.port=8082

新建ribbon-consumer maven项目

2、pom配置

<parent>    <groupId>org.springframework.cloud</groupId>    <artifactId>spring-cloud-starter-parent</artifactId>    <version>Brixton.SR4</version>    <relativePath/> </parent><dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-web</artifactId></dependency><dependency>  <groupId>org.springframework.cloud</groupId>  <artifactId>spring-cloud-starter-eureka</artifactId></dependency><dependency>  <groupId>org.springframework.cloud</groupId>  <artifactId>spring-cloud-starter-ribbon</artifactId></dependency>

2、application.properties

连接之前配置的注册中心地址,随意一个即可

spring.application.name=ribbon-consumerserver.port=9000eureka.client.serviceUrl.defaultZone=http://peer1:1111/eureka/

3、代码

RebbonConsumerApplication:
- 通过EnableDiscoveryClient发现服务
- 通过LoadBalanced开启负载均衡

package com.tan.self;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.client.loadbalancer.LoadBalanced;import org.springframework.context.annotation.Bean;import org.springframework.web.client.RestTemplate;/** * Author: Mr.tan * Date: 2017/9/9 */@EnableDiscoveryClient  // 获得服务发现能力@SpringBootApplicationpublic class RebbonConsumerApplication {    @Bean    @LoadBalanced         // 开启负载均衡    RestTemplate restTemplate(){        return new RestTemplate();    }    public static void main(String[] args) {        SpringApplication.run(RebbonConsumerApplication.class, args);    }}

ConsumerController:通过RestTemplate调用hello-service提供的服务

package com.tan.self;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.client.RestTemplate;/** * Author: Mr.tan * Date: 2017/9/9 */@RestControllerpublic class ConsumerController {    @Autowired    RestTemplate restTemplate;    @RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET)    public String helloConsumer(){        return restTemplate.getForEntity("http://hello-service/hello", String.class).getBody();    }}

4、启动

启动rebbon-consumer应用,通过http://localhost:9000/rebbon-consumer发起GET请求,调用服务,获取数据。

这里写图片描述

通过不断刷新请求,可以看到实现了负载均衡,Rebbon会轮询的方式调用两个应用。

这里写图片描述

三、Feign消费

Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。

简而言之:
Feign 采用的是基于接口的注解
Feign 整合了ribbon

接着上文的项目:RebbonConsumerApplication新增EnableFeignClients注解

1、新增依赖

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

2、代码实现

FeignService:通过@FeignClient指明服务的应用名,RequestMapping接口方法

@FeignClient(value = "hello-service")public interface FeignService {    @RequestMapping(value = "/hello",method = RequestMethod.GET)    String sayHiFromClientOne();}

修改ConsumerController,新增方法:

 @RequestMapping(value = "/feign", method = RequestMethod.GET)    public String feignConsumer(){        return feignService.sayHiFromClientOne();    }

3、验证

重新启动项目,访问 http://localhost:9000/feign,返回hello world

四、断路

Spring Cloud应用程序能够通过添加spring-cloud-starter-hystrix关联性并将其配置类与@EnableCircuitBreaker相整合的方式利用Hystrix。在此之后,大家可以通过与@HystrixCommand整合的方式将断路器机制纳入到任意Spring Bean方法内

1、引入对应jar

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

2、代码实现

在之前的RebbonConsumerApplication类上新增@EnableCircuitBreaker ,用于配置断路器enable.

修改ConsumerController:在需要实现断路的方法上新增@HystrixCommand,配置fallbackMethod ,该断路器处于断开状态时,此方法将替代接受调用:

@RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET)@HystrixCommand(fallbackMethod = "helloFallback")public String helloConsumer(){    return restTemplate.getForEntity("http://hello-service/hello", String.class).getBody();}@RequestMapping(value = "/ribbon-consumer-no", method = RequestMethod.GET)public String helloNoHystrixConsumer(){    return restTemplate.getForEntity("http://hello-service/hello", String.class).getBody();}public String helloFallback() {    return "hello world fallback";}

3、验证

重新启动consumer项目,停掉之前的hello-service,分别访问

http://localhost:9000/ribbon-consumer 和
http://localhost:9000/ribbon-consumer-no

未加HystrixCommand注解的,会报Connection refused: connect 500 异常,
新增HystrixCommand注解的,返回call back替代方法的数据。

完整项目代码在:https://github.com/hanmo9/spring-cloud-learn

阅读全文
0 0