hystrix如何使用

本文介绍了Hystrix作为服务容错管理工具的原理和作用,通过在SpringCloud中添加相关依赖,配置服务超时及启用熔断器,确保系统在服务不稳定时保持弹性。同时,展示了如何通过@FeignClient配合Hystrix进行服务降级,保证整体系统的稳定性。
摘要由CSDN通过智能技术生成

1. Hystrix概念

Hystrix 是一个供分布式系统使用,提供延迟和容错功能,保证复杂的分布系统在面临不可避免的失败时,仍能有其弹性。

比如系统中有很多服务,当某些服务不稳定的时候,使用这些服务的用户线程将会阻塞,如果没有隔离机制,系统随时就有可能会挂掉,从而带来很大的风险。SpringCloud使用Hystrix组件提供断路器、资源隔离与自我修复功能。

说简单点就是它在系统某些服务出问题的时候,有备选方案,不至于让整个系统挂掉

2. 添加依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<!--hystrix依赖,主要是用  @HystrixCommand -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!--服务注册-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--服务调用-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

3. 添加配置

feign.hystrix.enabled=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000

4. 添加熔断器的实现类

之前用feign的时候我们用了一个接口+@FeignClient的方式进行了调用,

我们实现这个接口并实现他的所有方法。这样返回的类型就一样了。

5. 指定服务降级

@FeignClient注解稍加改变

@FeignClient("service") // 这个是被调用方的spring.application.name
@Component // 给spring管理,之后要用的
public interface TestClient {
    @DeleteMapping(value = "/test/{userId}")
    public Response test(@PathVariable("userId") String userId);
}

改成这样即可

@FeignClient(name = "service", fallback="TestClientImpl.class") // 这个是被调用方的spring.application.name
@Component // 给spring管理,之后要用的
public interface TestClient {
    @DeleteMapping(value = "/test/{userId}")
    public Response test(@PathVariable("userId") String userId);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值