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

一、服务注册

新建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
 */
@RestController
public 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=8081
java -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-consumer
server.port=9000

eureka.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  // 获得服务发现能力
@SpringBootApplication
public 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
 */
@RestController
public 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值