hystrix如何使用

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);
}

猜你喜欢

转载自blog.csdn.net/weixin_43795939/article/details/113763856