hystrix功能:
1、 资源隔离。就是对对应的接口分配线程池,避免说对一个接口的过多调用,因为依赖服务接口调用的失败或者延迟,导致所有的线程资源都全部耗费在这个接口上。一旦某个服务的线程资源全部耗尽可能导致服务的崩溃,甚至故障蔓延。
2、降级机制。超时降级、资源不足时(线程或信号量)降级,降级后可以配合降级接口返回托底数据。
下面是springboot和hystrix的整合案例:
下面需要用到maven依赖,主要是springboot版本和hystrix有对应关系。
<!--这是springboot的版本-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--下面是关于hystrix的依赖-->
<-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>1.4.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
</dependency>
初始化需要用到 HystrixCommandAspect 和 ServletRegistrationBean
@Configuration
public class HystrixConfig {
//用来拦截处理HystrixCommand注解
@Bean
public HystrixCommandAspect hystrixAspect() {
return new HystrixCommandAspect();
}
//用来像监控中心Dashboard发送stream信息
@Bean
public ServletRegistrationBean hystrixMetricsStreamServlet() {
ServletRegistrationBean registration = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
registration.addUrlMappings("/hystrix.stream");
return registration;
}
}
3、对需要熔断的接口进行配置
@PostMapping("/test/netflix")
@HystrixCommand(
fallbackMethod = "netflixFallback",
threadPoolProperties = {
@HystrixProperty(name = "coreSize",value = "10"),
@HystrixProperty(name = "maxQueueSize", value = "2"),
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "10")},
commandProperties = {
//命令执行超时时间10s
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000"),
//若干10s一个窗口内失败三次, 则达到触发熔断的最少请求量
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2"),
//断路3s后尝试执行, 默认为5s
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "3000")
}
)
public JsonVO testNetflix(@RequestBody PageVO pageVO){
LOGGER.error("/test/netflix receive a message");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new JsonVO<>(200, "success");
}
public JsonVO netflixFallback(@RequestBody PageVO pageVO){
LOGGER.error("comming netflix");
return new JsonVO<>(500, "comming netflix");
}
}
后面附上测试代码,这里创造50个并发,查看测试结果。
@Test
public void contextLoads() {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("pageNum", String.valueOf(1));
paramMap.put("pageSize", String.valueOf(10));
String jsonParam = JSON.toJSONString(paramMap);
CountDownLatch endCount = new CountDownLatch(50);
CountDownLatch beginCount = new CountDownLatch(1);
Thread[] threads = new Thread[50];
//起50线程测试