Hystrix 服务熔断
 · 阅读需 3 分钟
Hystrix官方文档 在需要进行服务熔断的服务pom文件添加依赖
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  <version>2.2.10.RELEASE</version>
</dependency>
启动类添加注解 @EnableHystrix
服务降级 @HystrixCommand
@RestController
@RequestMapping("/borrows")
public class BorrowController {
    @Resource
    private BorrowService borrowService;
    @HystrixCommand(fallbackMethod = "onError")    //使用@HystrixCommand来指定备选方案
    @GetMapping("/{uid}")
    public UserBorrowDetail findUserBorrowDetailByUid(@PathVariable int uid){
        return borrowService.getUserBorrowDetailByUid(uid);
    }
    //备选方案,这里直接返回空列表了
    //注意参数和返回值要和上面的一致
    UserBorrowDetail onError(int uid){
        return new UserBorrowDetail(null, Collections.emptyList());
    }
}
服务熔断 Circuit Breaker
在一段时间内多次调用失败,那么从服务降级直接升级为熔断。
使用OpenFeign实现降级 @FeignClient
Feign
给需要添加服务的 Client 添加fallback 属性
@FeignClient(value = "UserService",fallback = UserFallbackClient.class)
实现Client类
@Component   //注意,需要将其注册为Bean,Feign才能自动注入
public class UserFallbackClient implements UserClient{
    @Override
    public User getUserById(int uid) {   //这里我们自行对其进行实现,并返回我们的替代方案
        User user = new User();
        user.setName("我是替代方案");
        return user;
    }
}
在该服务的application.xml中配置feign ,可以取消BorrowController 的@HystrixCommand注解
feign:
  circuitbreaker:
    enabled: true
此时如果UserService 挂掉,会执行UserFallbackClient的替代方案
监控面板 Hystrix Dashboard
新建一个 Hystrix Dashboard 服务
添加依赖
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
  <version>2.2.10.RELEASE</version>
</dependency>
添加配置文件 application.yml
server:
  port: 8900
hystrix:
  dashboard:
    # 将localhost添加到白名单,默认是不允许的
    proxy-stream-allow-list: "localhost"
访问服务:本地 Hystrix Dashboard 服务
 为需要监控的微服务添加
为需要监控的微服务添加actuator依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>