Spring Cloud使用Hystrix

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忽略的异常。上面讲的这些基本能满足我们一般的需求了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值