1. 添加必要依赖
<!-- Hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.9.RELEASE</version>
</dependency>
2. 修改配置文件
在application.yml中开启熔断器
spring:
cloud:
#开启hystrix熔断器
circuitbreaker:
hystrix:
enabled: true
3. 在消费者服务的启动类添加注解
// @EnableHystrix 包含 @EnableCircuitBreaker
@EnableHystrix
@EnableFeignClients
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
4. 在源码中使用
基于Fegin的服务调用
@RestController
public class HelloController {
@Autowired
private HelloFeignService helloFeignService ;
@GetMapping("/hello")
@HystrixCommand(fallbackMethod = "helloError")
public String call() {
// 像调用本地服务一样
return helloFeignService.hello();
}
//熔断回调方法,名称一定要和fallbackMethod中的一样
public String helloError(){
return "终于熔断了...";
}
}
补充:HelloFeignService 接口
//表示我们需要调用已在服务注册中心注册过的服务是my-producer
@FeignClient(name = "my-producer" )
public interface HelloFeignService {
@GetMapping("/hello")
public String hello();
// 添加跟调用目标一样的方法声明,二者保持一致即可,不需要实现
}