接着上一篇的Hystrix进行进一步了解。git
当系统用户不断增加时,每一个微服务须要承受的并发压力也愈来愈大,在分布式环境中,一般压力来自对依赖服务的调用,由于亲戚依赖服务的资源须要经过通讯来实现,这样的依赖方式比起进程内的调用方式会引发一部分的性能损失,github
在高并发的场景下,Hystrix 提供了请求缓存的功能,咱们能够方便的开启和使用请求缓存来优化系统,达到减轻高并发时的请求线程消耗、下降请求响应时间的效果spring
Hystrix的缓存,这个功能是有点鸡肋的,由于这个缓存是基于request的,为何这么说呢?由于每次请求来以前都必须HystrixRequestContext.initializeContext();进行初始化,每请求一次controller就会走一次filter,上下文又会初始化一次,前面缓存的就失效了,又得从新来。数据库
因此你要是想测试缓存,你得在一次controller请求中屡次调用那个加了缓存的service或HystrixCommand命令。Hystrix的书上写的是:在同一用户请求的上下文中,相同依赖服务的返回数据始终保持一致。在当次请求内对同一个依赖进行重复调用,只会真实调用一次。在当次请求内数据能够保证一致性。浏览器
所以。但愿你们在这里不要理解错了。缓存
请求缓存图,以下:tomcat
假设两个线程发起相同的HTTP请求,Hystrix会把请求参数初始化到ThreadLocal中,两个Command异步执行,每一个Command会把请求参数从ThreadLocal中拷贝到Command所在自身的线程中,Command在执行的时候会经过CacheKey优先从缓存中尝试获取是否已有缓存结果,网络
若是命中,直接从HystrixRequestCache返回,若是没有命中,那么须要进行一次真实调用,而后把结果回写到缓存中,在请求范围内共享响应结果。并发
RequestCache主要有三个优势:app
在当次请求内对同一个依赖进行重复调用,只会真实调用一次。
在当次请求内数据能够保证一致性。
能够减小没必要要的线程开销。
例子仍是接着上篇的HelloServiceCommand来进行演示,咱们只须要实现HystrixCommand的一个缓存方法名为getCacheKey()便可
代码以下:
/** * Created by cong on 2018/5/9. */ public class HelloServiceCommand extends HystrixCommand<String> { private RestTemplate restTemplate; protected HelloServiceCommand(String commandGroupKey,RestTemplate restTemplate) {
//根据commandGroupKey进行线程隔离的 super(HystrixCommandGroupKey.Factory.asKey(commandGroupKey)); this.restTemplate = restTemplate; } @Override protected String run() throws Exception { System.out.println(Thread.currentThread().getName()); return restTemplate.getForEntity("http://HELLO-SERVICE/hello",String.class).getBody(); } @Override protected String getFallback() { return "error"; } //Hystrix的缓存 @Override protected String getCacheKey() { //通常动态的取缓存Key,好比userId,这里为了作实验写死了,写为hello return "hello"; } }
Controller代码以下:
/** * Created by cong on 2018/5/8. */ @RestController public class ConsumerController { @Autowired private RestTemplate restTemplate; @RequestMapping("/consumer") public String helloConsumer() throws ExecutionException, InterruptedException { //Hystrix的缓存实现,这功能有点鸡肋。 HystrixRequestContext.initializeContext(); HelloServiceCommand command = new HelloServiceCommand("hello",restTemplate); String execute = command.execute();//清理缓存 // HystrixRequestCache.getInstance("hello").clear(); return null; } }
在原来的两个provider模块都增长增长一条输出语句,以下:
provider1模块:
/** * Created by cong on 2018/5/8. */ @RestController public class HelloController { @RequestMapping("/hello") public String hello(){ System.out.println("访问来1了......"); return "hello1"; } }
provider2模块:
/** * Created by cong on 2018/5/8. */ @RestController public class HelloController { @RequestMapping("/hello") public String hello(){ System.out.println("访问来2了......"); return "hello1"; } }
浏览器输入localhost:8082/consumer
运行结果以下:
能够看到你刷新一次请求,上下文又会初始化一次,前面缓存的就失效了,又得从新来,这时候根本就没有缓存了。所以,你不管刷新多少次请求都是出现“访问来了”,缓存都是失效的。若是是从缓存来的话,根本就不会输出“访问来了”。
可是,你如你在一块儿请求屡次调用同一个业务,这时就是从缓存里面取的数据。不理解能够看一下Hystrix的缓存解释:在同一用户请求的上下文中,相同依赖服务的返回数据始终保持一致。在当次请求内对同一个依赖进行重复调用,只会真实调用一次。在当次请求内数据能够保证一致性。
Controller代码修改以下:
/** * Created by cong on 2018/5/8. */ @RestController public class ConsumerController { @Autowired private RestTemplate restTemplate; @RequestMapping("/consumer") public String helloConsumer() throws ExecutionException, InterruptedException { //Hystrix的缓存实现,这功能有点鸡肋。 HystrixRequestContext.initializeContext(); HelloServiceCommand command = new HelloServiceCommand("hello",restTemplate); String execute = command.execute();
HelloServiceCommand command1 = new HelloServiceCommand("hello",restTemplate);
String execute1 = command1.execute();
//清理缓存
// HystrixRequestCache.getInstance("hello").clear();
return null;
}
接着运行,运行结果以下:
能够看到只有一个”访问来了“,并无出现两个”访问来了“。
之因此没出现第二个,是由于是从缓存中取了。
删除缓存 例如删除key名为hello的缓存:
HystrixRequestCache.getInstance("hello").clear();
你要写操做的时候,你把一条数据给给删除了,这时候你就必须把缓存清空了。
下面进行请求的合并。
为何要进行请求合并?举个例子,有个矿山,每过一段时间都会生产一批矿产出来(质量为卡车载重量的1/100),卡车能够一等到矿产生产出来就立刻运走矿产,也能够等到卡车装满再运走矿产,
前者一次生产对应卡车一次往返,卡车须要往返100次,然后者只须要往返一次,能够大大减小卡车往返次数。显而易见,利用请求合并能够减小线程和网络链接,开发人员没必要单独提供一个批量请求接口就能够完成批量请求。
在Hystrix中进行请求合并也是要付出必定代价的,请求合并会致使依赖服务的请求延迟增高,延迟的最大值是合并时间窗口的大小,默认为10ms,固然咱们也能够经过hystrix.collapser.default.timerDelayInMilliseconds属性进行修改,
若是请求一次依赖服务的平均响应时间是20ms,那么最坏状况下(合并窗口开始是请求加入等待队列)此次请求响应时间就会变成30ms。在Hystrix中对请求进行合并是否值得主要取决于Command自己,高并发度的接口经过请求合并能够极大提升系统吞吐量,
从而基本能够忽略合并时间窗口的开销,反之,并发量较低,对延迟敏感的接口不建议使用请求合并。
请求合并的流程图以下:
能够看出Hystrix会把多个Command放入Request队列中,一旦知足合并时间窗口周期大小,Hystrix会进行一次批量提交,进行一次依赖服务的调用,经过充写HystrixCollapser父类的mapResponseToRequests方法,将批量返回的请求分发到具体的每次请求中。
例子以下:
首先咱们先自定义一个BatchCommand类来继承Hystrix给咱们提供的HystrixCollapser类,代码以下:
/** * Created by cong on 2018/5/13. */ public class HjcBatchCommand extends HystrixCollapser<List<String>,String,Long> { private Long id; private RestTemplate restTemplate; //在200毫秒内进行请求合并,不在的话,放到下一个200毫秒 public HjcBatchCommand(RestTemplate restTemplate,Long id) { super(Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("hjcbatch")) .andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter() .withTimerDelayInMilliseconds(200))); this.id = id; this.restTemplate = restTemplate; } //获取每个请求的请求参数 @Override public Long getRequestArgument() { return id; } //建立命令请求合并 @Override protected HystrixCommand<List<String>> createCommand(Collection<CollapsedRequest<String, Long>> collection) { List<Long> ids = new ArrayList<>(collection.size()); ids.addAll(collection.stream().map(CollapsedRequest::getArgument).collect(Collectors.toList())); HjcCommand command = new HjcCommand("hjc",restTemplate,ids); return command; } //合并请求拿到告终果,将请求结果按请求顺序分发给各个请求 @Override protected void mapResponseToRequests(List<String> results, Collection<CollapsedRequest<String, Long>> collection) { System.out.println("分配批量请求结果。。。。"); int count = 0; for (CollapsedRequest<String,Long> collapsedRequest : collection){ String result = results.get(count++); collapsedRequest.setResponse(result); } } }
接着用自定义个HjcCommand来继承Hystrix提供的HystrixCommand来进行服务请求
/** * Created by cong on 2018/5/13. */ public class HjcCommand extends HystrixCommand<List<String>> { private RestTemplate restTemplate; private List<Long> ids; public HjcCommand(String commandGroupKey, RestTemplate restTemplate,List<Long> ids) {
//根据commandGroupKey进行线程隔离 super(HystrixCommandGroupKey.Factory.asKey(commandGroupKey)); this.restTemplate = restTemplate; this.ids = ids; } @Override protected List<String> run() throws Exception { System.out.println("发送请求。。。参数为:"+ids.toString()+Thread.currentThread().getName()); String[] result = restTemplate.getForEntity("http://HELLO-SERVICE/hjcs?ids={1}",String[].class, StringUtils.join(ids,",")).getBody(); return Arrays.asList(result); } }
可是注意一点:你请求合并必需要异步,由于你若是用同步,是一个请求完成后,另外的请求才能继续执行,因此必需要异步才能请求合并。
因此Controller层代码以下:
@RestController public class ConsumerController { @Autowired private RestTemplate restTemplate; @RequestMapping("/consumer") public String helloConsumer() throws ExecutionException, InterruptedException { //请求合并 HystrixRequestContext context = HystrixRequestContext.initializeContext(); HjcBatchCommand command = new HjcBatchCommand(restTemplate,1L); HjcBatchCommand command1 = new HjcBatchCommand(restTemplate,2L); HjcBatchCommand command2 = new HjcBatchCommand(restTemplate,3L); //这里你必需要异步,由于同步是一个请求完成后,另外的请求才能继续执行,因此必需要异步才能请求合并 Future<String> future = command.queue(); Future<String> future1 = command1.queue(); String r = future.get(); String r1 = future1.get(); Thread.sleep(2000); //能够看到前面两条命令会合并,最后一条会单独,由于睡了2000毫秒,而你请求设置要求在200毫秒内才合并的。 Future<String> future2 = command2.queue(); String r2 = future2.get(); System.out.println(r); System.out.println(r1); System.out.println(r2); context.close(); return null; } }
两个服务提供者provider1,provider2新增长一个方法来模拟数据库数据,代码以下:
/** * Created by cong on 2018/5/8. */ @RestController public class HelloController { @RequestMapping("/hello") public String hello(){ System.out.println("访问来2了......"); return "hello2"; } @RequestMapping("/hjcs") public List<String> laowangs(String ids){ List<String> list = new ArrayList<>(); list.add("laowang1"); list.add("laowang2"); list.add("laowang3"); return list; } }
启动Ribbon模块,运行结果以下:
能够看到上图的两个线程是隔离的。
当请求很是多的时候,你合并请求就变得很是重要了,若是你不合并,一个请求都1 到2秒,这明显不能忍的,会形成效率缓慢,若是你合并后,这时就能够并行处理,下降延迟,可是若是请求很少的时候,只有单个请求,这时候合并也会出现
效率缓慢的,由于若是请求一次依赖服务的平均响应时间是200ms,那么最坏状况下(合并窗口开始是请求加入等待队列)此次请求响应时间就会变成300ms。因此说要看场合而定的。
下面用注解的代码来实现请求合并。代码以下:‘
/** * Created by cong on 2018/5/15. */ @Service public class HjcService { @Autowired private RestTemplate restTemplate; @HystrixCollapser(batchMethod = "getLaoWang",collapserProperties = {@HystrixProperty(name = "timerDelayInMilliseconds",value = "200")}) public Future<String> batchGetHjc(long id){ return null; } @HystrixCommand public List<String> getLaoWang(List<Long> ids){ System.out.println("发送请求。。。参数为:"+ids.toString()+Thread.currentThread().getName()); String[] result = restTemplate.getForEntity("http://HELLO-SERVICE/hjcs?ids={1}",String[].class, StringUtils.join(ids,",")).getBody(); return Arrays.asList(result); } }
若是咱们还要进行服务的监控的话,那么咱们须要在Ribbon模块,和两个服务提供者模块提供以下依赖:
Ribbon模块依赖以下:
<!--仪表盘--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId> <version>1.4.0.RELEASE</version> </dependency> <!--监控--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-actuator</artifactId> </dependency>
两个provider模块依赖以下:
<!--监控--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-actuator</artifactId> </dependency>
接着在Ribbon启动类打上@EnableHystrixDashboard注解,而后启动,localhost:8082/hystrix,以下图:
每次访问都有记录:以下:
接下来咱们看一下经常使用的Hystrix属性:
hystrix.command.default和hystrix.threadpool.default中的default为默认CommandKey
hystrix.command.default.execution.isolation.strategy 隔离策略,默认是Thread, 可选Thread|Semaphore
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds 命令执行超时时间,默认1000ms
这些参数能够应用于Hystrix的THREAD和SEMAPHORE策略
hystrix.command.default.requestCache.enabled 默认true,须要重载getCacheKey(),返回null时不缓存
hystrix.command.default.requestLog.enabled 记录日志到HystrixRequestLog,默认true
hystrix.collapser.default.maxRequestsInBatch 单次批处理的最大请求数,达到该数量触发批处理,默认Integer.MAX_VALUE
hystrix.collapser.default.timerDelayInMilliseconds 触发批处理的延迟,也能够为建立批处理的时间+该值,默认10
hystrix.collapser.default.requestCache.enabled 是否对HystrixCollapser.execute() and HystrixCollapser.queue()的cache,默认true
线程数默认值10适用于大部分状况(有时能够设置得更小),若是须要设置得更大,那有个基本得公式能够follow:
requests per second at peak when healthy × 99th percentile latency in seconds + some breathing room
每秒最大支撑的请求数 (99%平均响应时间 + 缓存值)
好比:每秒能处理1000个请求,99%的请求响应时间是60ms,那么公式是:
1000 (0.060+0.012)
基本得原则时保持线程池尽量小,他主要是为了释放压力,防止资源被阻塞。
当一切都是正常的时候,线程池通常仅会有1到2个线程激活来提供服务