一、环境
jdk:12
spring cloud:Greenwich.RELEASE
spring boot:2.1.0.RELEASE
spring-cloud-starter-feign:2.0.0.M2
eurekaServer: 前面提到用于服务注册
eurekaClient: 前面提到用于提供服务
serviceConsumer:前面提到服务消费工程
二、修改服务消费工程
1.pom.xml文件中增加spring-cloud-starter-netflix-hystrix依赖:
...........
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
...........
2.配置文件 application.yml 增加配置打开 hystrix 功能
..................
feign:
hystrix:
enabled: true
..................
Feign中集成了Hystrix,但是默认没有启用,所以需要增加此配置
- 启动类 ServiceConsumerApplication.java 增加 @EnableCircuitBreaker 以打开熔断功能
package com.bry.springcloud.eurekaclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableCircuitBreaker
public class ServiceConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceConsumerApplication.class, args);
}
}
增加@EnableCircuitBreaker表示启用熔断机制
4.给接口HelloService开发一个实现类 HelloServiceHystrix.java
package com.bry.springcloud.eurekaclient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
@Service
public class HelloServiceHystrix implements HelloService {
public String sayHello(@RequestParam(value = "name") String name) {
return "Hello " + name + " Error occurred! This is default message";
}
}
此类用在调用远程HelloService服务失败时供Feign调用返回一个默认结果。
5.修改HelloService.java,增加callback类配置
package com.bry.springcloud.eurekaclient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(value = "eurekaClient", fallback = HelloServiceHystrix.class)
public interface HelloService {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello(@RequestParam(value = "name") String name);
}
fallback = HelloServiceHystrix.class表示当这个类中的方法调用出错时,改调用HelloServiceHystrix.class
的实例中的方法。
三、测试
1.启动eurekaServer工程。
2.启动serviceConsumer工程
3.访问前面的测试服务 http://localhost:6545/testhello?name=bruce
4.启动eurekaClient工程
5.等2分钟后再访问前面的测试服务 http://localhost:6545/testhello?name=bruce
参考
https://blog.csdn.net/forezp/article/details/81040990
https://projects.spring.io/spring-cloud/spring-cloud.html#_circuit_breaker_hystrix_clients
备注:
可以从 https://github.com/zhoupinheng/springclouddemo 下载完整代码。