Hystrix服务降级

发布时间 2023-07-17 12:11:42作者: 天晴修屋顶

        Hystrix是Netflix开源的一款用于实现服务容错和服务降级的库。在微服务架构中,服务之间存在依赖关系,当某个服务发生故障或延迟过高时,可能会导致整个系统不可用。Hystrix通过提供服务降级、熔断、限流等机制,帮助提高系统的稳定性和可靠性。

       服务降级是Hystrix的一项重要功能,它通过在发生故障时,将失败的服务请求快速地返回一个备选响应(如缓存数据、默认值),而不是让用户长时间地等待。服务降级可以有效地控制故障的扩散,避免整个系统崩溃。

一、引入依赖

1     <dependency>
2       <groupId>org.springframework.cloud</groupId>
3       <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
4     </dependency>
application.yml

二、启动Hystrix

在启动类上使用@EnableCircuitBreaker注解来启用Hystrix断路器。

 1 import org.springframework.boot.SpringApplication;
 2 import org.springframework.boot.autoconfigure.SpringBootApplication;
 3 import org.springframework.cloud.netflix.hystrix.EnableHystrix;
 4 import org.springframework.cloud.openfeign.EnableFeignClients;
 5 
 6 /**
 7  * @Classname HystrixApplication
 8  * @Created by Michael
 9  * @Date 2023/7/17
10  * @Description 服务降级
11  */
12 @SpringBootApplication
13 @EnableFeignClients
14 @EnableHystrix
15 public class HystrixApplication {
16   public static void main(String[] args) {
17     SpringApplication.run(HystrixApplication.class,args);
18   }
19 }
HystrixApplication

三、定义服务降级逻辑
在需要进行服务降级的方法上,通过@HystrixCommand注解定义降级逻辑,并指定备用方法。

 1 import com.mike.study.hystrix.client.UserClient;
 2 import com.mike.study.hystrix.vo.HttpResponseResult;
 3 import com.mike.study.hystrix.vo.UserVo;
 4 import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
 5 import com.netflix.ribbon.proxy.annotation.Hystrix;
 6 import org.springframework.http.HttpStatus;
 7 import org.springframework.web.bind.annotation.GetMapping;
 8 import org.springframework.web.bind.annotation.PathVariable;
 9 import org.springframework.web.bind.annotation.RestController;
10 
11 import javax.annotation.Resource;
12 
13 /**
14  * @Classname HystrixController
15  * @Created by Michael
16  * @Date 2023/7/17
17  * @Description 服务降级
18  */
19 @RestController
20 public class HystrixController {
21   @Resource
22   private UserClient userClient;
23 
24   @GetMapping("hystrix/user/{id}")
25   @HystrixCommand(fallbackMethod = "getUserFallback")
26   public HttpResponseResult getUser(@PathVariable("id") Integer userId) {
27     System.out.println("使用feign框架调用provide的api");
28     UserVo userVo = userClient.getUser(userId);
29     HttpResponseResult result = new HttpResponseResult<UserVo>();
30     result.setStatusCode(HttpStatus.OK.value());
31     result.setMessage(HttpStatus.OK.getReasonPhrase());
32     result.setData(userVo);
33     return result;
34   }
35 
36   /**
37    * 获取用户信息降级处理
38    * @param userId
39    * @return friendly info
40    */
41   public HttpResponseResult getUserFallback(Integer userId) {
42     HttpResponseResult result = new HttpResponseResult<UserVo>();
43     result.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
44     result.setMessage(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
45     result.setData(new UserVo());
46     return result;
47   }
Controller

注意,降级方法必须和原方法同参数,同返回值。可以给每个需要降级的服务指定降级方法,也可以统一设置降级方法。统一降级则在类上添加注解@DefaultProperties(defaultFallback="defaultFallBack")

四、 配置hystrix属性

 1 hystrix:
 2   command:
 3     default:
 4       circuitBreaker:
 5         errorThresholdPercentage: 10 # 设置失败比例阀值
 6         sleepWindowInMilliseconds: 10000 # 设置休眠时间(根据业务来设置)
 7       exectuion:
 8         isolation:
 9           thread:
10             timeoutInMilliseconds: 2000 # 超时时间
11   threadpool:
12     default:
13       allowMaximumSizeToDivergeFromCoreSize: true # 让最大线程数生效
14       coreSize: 5 #设置线程池最小线程数
15       maxQueueSize: 10 #设置队列长度
16       maximumSize: 10 #设置最大线程池数量

五、测试

5.1 准备provider,提供查询数据库信息的api,Hystrix module通过feign框架调佣provider的api。目录结构如下

 5.2 分别启动hystrix和provider module,正常访问

5.3 停掉provider服务,访问同样地址

 可以看到服务正常响应,但是是降级后的响应结果。当provider重启启动恢复正常,需要等待一会,hystrix才会恢复正常访问。