1.hystrix核心功能:
资源隔离。就是多个依赖服务的调用分别隔离到各自自己的资源池内。避免说对一个依赖服务的调用,因为依赖服务接口调用的失败或者延迟,导致所有的线程资源
都全部耗费在这个接口上。一旦某个服务的线程资源全部耗尽可能导致服务的崩溃,甚至故障蔓延。 2.资源隔离的方法
信号量semaphore,最多能容纳10个请求。一旦超过10个信号量最大容量,那么就会拒绝其他请求。
信号量与线程池资源隔离的区别:
线程池隔离技术并非控制tomcat等web容器的线程。更准确的说就是控制tomcat线程的执行。tomcat接到请求之后会调用hystrix线程池的线程去执行。当线程池满了之后会调用fallback降级。
tomcat其他的线程不会卡死,快速返回,然后可以支撑其他事情。同时hystrix处理timeout超时问题。
信号量隔离只是一个关卡,通过我的关卡的线程是固定的。容量满了之后。fallback降级。
区别:线程池隔离技术是用自己的线程去执行调用。信号量是直接让tomcat线程去执行依赖服务。
2.hystrix整合springboot
(1) java 代码
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
@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;
}
}
@GetMapping
@LogAnnotation(module = LogModule.GET_USER_BYID)
@HystrixCommand(
fallbackMethod = "getByIdFallback",
threadPoolProperties = { //10个核心线程池,超过20个的队列外的请求被拒绝; 当一切都是正常的时候,线程池一般仅会有1到2个线程激活来提供服务
@HystrixProperty(name = "coreSize", value = "10"),
@HystrixProperty(name = "maxQueueSize", value = "100"),
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "20")},
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000"), //命令执行超时时间
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2"), //若干10s一个窗口内失败三次, 则达到触发熔断的最少请求量
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "30000") //断路30s后尝试执行, 默认为5s
})
private static int num = 1;
public User getById(Long id) {
if(num == 1) {
num = 0;
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
num = 1;
}
return userService.getById(id);
}
public User getByIdFallback(Long id) {
throw new HystrixException("服务器负载过重,请稍后请求!");
}
(2)Hystrix-Dashboard使用
①下载https://bintray.com/kennedyoliveira/maven/standalone-hystrix-dashboard/1.5.6
②运行nohup java -jar standalone-hystrix-dashboard-1.5.6-all.jar &
③浏览器打开http://localhost:7979/hystrix-dashboard/ 输入地址http://127.0.0.1/hystrix.stream
先点击 add stream
然后点击monitor stream既可以查看