Hystrix 旨在通过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。Hystrix具备拥有回退机制和断路器功能的线程和信号隔离,请求缓存和请求打包,以及监控和配置等功能。
1、引入spring-cloud-starter-netflix-hystrix依赖
<!-- hystrix服务熔断-->
<!-- 注意要选择与springboot对应的版本,否则会报错 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>
2、在主程序类上增加注解@EnableHystrix来开启hystrix功能
@EnableHystrix //开启服务熔断
@SpringBootApplication
public class SpringbootServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootServiceProviderApplication.class, args);
}
}
3、在服务提供者Provider上增加@HystrixCommand注解,这样调用就会经过Hystrix代理。
@Service //暴露服务
@Component
public class UserServiceImpl implements UserService {
@HystrixCommand //表示方法被hystrix代理,出现异常就可以熔断了
@Override
public List<UserAddress> getUserAddressList(String userId) {
UserAddress address1 = new UserAddress(1, "北京市昌平区宏福科技园综合楼3层", "1", "李老师", "010-56253825", "Y");
UserAddress address2 = new UserAddress(2, "深圳市宝安区西部硅谷大厦B座3层(深圳分校)", "1", "王老师", "010-56253825", "N");
if(Math.random()>0.5){
throw new RuntimeException();
}
return Arrays.asList(address1,address2);
}
}
4、在服务消费者增加@HystrixCommand注解并指定出错时的回调方法。当调用出错时,会调用fallbackMethod = "hello"里面的指定的hello方法。
@Service
public class OrderServiceImpl implements OrderService {
@Reference
UserService userService;
/**当方法报错时,由回调方法hello处理*/
@HystrixCommand(fallbackMethod = "hello")
@Override
public List<UserAddress> initOrder(String userId) {
System.out.println("用户id:"+userId);
//1、查询用户的收货地址
List<UserAddress> userAddressList = userService.getUserAddressList(userId);
return userAddressList;
}
/**服务熔断的回调方法*/
public List<UserAddress> hello(String userId) {
return Arrays.asList(new UserAddress(10,"服务熔断测试","1","服务熔断测试","服务熔断测试","Y"));
}
}