Hystrix是在消费服务上搭建的,因为服务消费者能直接感知服务生产者的可用性,当发现服务生产者不可用时,那么服务消费将发生熔断,减少调用其他服务或停止调用其他服务,接入Hystrix的操作流程如下:
第一、添加pom依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
同时我们也可以使用actuator来监控服务的状态,这里是为了看Hystrix的状态,我们不妨加上他的pom依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
第二、相关配置
# actuator对外端口
management.port=8023
# 默认情况下,Hystrix接口是通过线程池中线程来调用
# 线程池相关参数
hystrix.threadpool.default.coreSize=1
hystrix.threadpool.default.maxQueueSize=1
hystrix.threadpool.default.maximumSize=1
# 此值为true上面的maximumSize才能生效
hystrix.threadpool.default.allowMaximumSizeToDivergeFromCoreSize=true
# 线程中执行超时时间,毫秒
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=2000
# 熔断阈值,自带百分号
hystrix.command.default.circuitBreaker.errorThresholdPercentage=10
# 熔断后休眠时间,毫秒
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds=10000
# 可以对特定接口单独指定配置
# hystrix.threadpool.mygroup.coreSize=3,通过@DefaultProperties(groupKey="mygroup")里应外合
第三、代码使用注解,类上面要加@DefaultProperties注解,方法上加@HystrixCommand注解
@Repository
@DefaultProperties(groupKey = "userDao",
commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")},
threadPoolProperties = {@HystrixProperty(name = "coreSize", value = "10")
, @HystrixProperty(name = "maxQueueSize", value = "1000")},
threadPoolKey = "userDao")
public class UserDao {
@HystrixCommand
public List<User> getUserList(User query) {
......
}
@HystrixCommand(fallbackMethod = "getUserByTokenFb", ignoreExceptions = IOException.class)
public User getUserByToken(String token) {
String url = "http://" + userServiceName + "/user/get?token=" + token;
ResponseEntity<RestResponse<User>> responseEntity = rest.get(url, new ParameterizedTypeReference<RestResponse<User>>() {
});
RestResponse<User> response = responseEntity.getBody();
if (response == null || response.getCode() != 0) {
return null;
}
return response.getResult();
}
public User getUserByTokenFb(String token) {
return new User();
}
}
这样就可以达到熔断的效果了,其中fallbackMethod参数指定的是熔断发生时的回调,需要我们注意的是,如果是业务异常,也会被Hystrix捕获,所以这时我们需要通过ignoreExceptions参数来指定让Hystrix忽略的异常。上面讲的这些基本能满足我们一般的需求了。