简介

在Hystrix中有个Request的概念,有一些操作需要在request中进行

缓存

在Hystrix调用服务时,如果只是查询接口,可以使用缓存进行优化,从而跳过真实访问请求。

应用

需要启用缓存的话需要重写command中getCacheKey方法

    @Override
protected String getCacheKey() {
return String.valueOf(value);
}

之后就可以调用了

但是如果直接调用command的运行相关方法会得到以下错误

Caused by: java.lang.IllegalStateException: Request caching is not available. Maybe you need to initialize the HystrixRequestContext?

这里说需要初始化HystrixRequestContext,在Hystrix中带缓存的command是必须在request中调用的。

public void testWithCacheHits() {
//初始化context
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
//两个一样的command
CommandUsingRequestCache command2a = new CommandUsingRequestCache(2);
CommandUsingRequestCache command2b = new CommandUsingRequestCache(2); assertTrue(command2a.execute());
// 第一次调用的返回是否从cache获得是false
assertFalse(command2a.isResponseFromCache()); assertTrue(command2b.execute());
// 第而次调用的返回是否从cache获得是true
assertTrue(command2b.isResponseFromCache());
} finally {
//关闭context
context.shutdown();
}
}

在不同context中的缓存是不共享的,还有这个request内部一个ThreadLocal,所以request只能限于当前线程

更新缓存

如果服务同时有更新的操作,那么在request中需要将原先的缓存失效

public static class GetterCommand extends HystrixCommand<String> {
//getter key 用于命名当前command,之后清楚缓存时需要
private static final HystrixCommandKey GETTER_KEY = HystrixCommandKey.Factory.asKey("GetterCommand");
private final int id; public GetterCommand(int id) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GetSetGet"))
.andCommandKey(GETTER_KEY));
this.id = id;
} @Override
protected String run() {
return prefixStoredOnRemoteDataStore + id;
} @Override
protected String getCacheKey() {
return String.valueOf(id);
} /**
* Allow the cache to be flushed for this object.
*/
public static void flushCache(int id) {
//这里从HystrixRequestCache的getInstance静态方法中找到对应实例,并将响应值清除
HystrixRequestCache.getInstance(GETTER_KEY,
HystrixConcurrencyStrategyDefault.getInstance()).clear(String.valueOf(id));
}
}

Collapser

Collapser可以合并多个请求一起调用

//需要定义一个Collapser
public class CommandCollapserGetValueForKey extends HystrixCollapser<List<String>, String, Integer> { private final Integer key; public CommandCollapserGetValueForKey(Integer key) {
this.key = key;
} @Override
public Integer getRequestArgument() {
return key;
} @Override
protected HystrixCommand<List<String>> createCommand(final Collection<CollapsedRequest<String, Integer>> requests) {
return new BatchCommand(requests);
} @Override
protected void mapResponseToRequests(List<String> batchResponse, Collection<CollapsedRequest<String, Integer>> requests) {
int count = 0;
for (CollapsedRequest<String, Integer> request : requests) {
request.setResponse(batchResponse.get(count++));
}
}
//底层command实现
private static final class BatchCommand extends HystrixCommand<List<String>> {
private final Collection<CollapsedRequest<String, Integer>> requests; private BatchCommand(Collection<CollapsedRequest<String, Integer>> requests) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
.andCommandKey(HystrixCommandKey.Factory.asKey("GetValueForKey")));
this.requests = requests;
}
//内部还是遍历入参进行调用
@Override
protected List<String> run() {
ArrayList<String> response = new ArrayList<String>();
for (CollapsedRequest<String, Integer> request : requests) {
// artificial response for each argument received in the batch
response.add("ValueForKey: " + request.getArgument());
}
return response;
}
}
} @Test
public void testCollapser() throws Exception {
//初始化request
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
//直接调用collapser
Future<String> f1 = new CommandCollapserGetValueForKey(1).queue();
Future<String> f2 = new CommandCollapserGetValueForKey(2).queue();
Future<String> f3 = new CommandCollapserGetValueForKey(3).queue();
Future<String> f4 = new CommandCollapserGetValueForKey(4).queue(); assertEquals("ValueForKey: 1", f1.get());
assertEquals("ValueForKey: 2", f2.get());
assertEquals("ValueForKey: 3", f3.get());
assertEquals("ValueForKey: 4", f4.get());
//只调用了一次command
// assert that the batch command 'GetValueForKey' was in fact
// executed and that it executed only once
assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size());
HystrixCommand<?> command = HystrixRequestLog.getCurrentRequest().getExecutedCommands().toArray(new HystrixCommand<?>[1])[0];
// assert the command is the one we're expecting
assertEquals("GetValueForKey", command.getCommandKey().name());
// confirm that it was a COLLAPSED command execution
assertTrue(command.getExecutionEvents().contains(HystrixEventType.COLLAPSED));
// and that it was successful
assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
} finally {
//关闭request
context.shutdown();
}
}

Collapser可以用来一起调用一批请求,在第一个调用get时会对积压的command一起调用。

总结

Hystrix的Request主要就是cache和collapser用到。在一般web应用中可以在filter中加入context的初始化和关闭逻辑。还要注意request是不支持跨线程。

Hystrix框架5--请求缓存和collapser的更多相关文章

  1. SpringCloud实战-Hystrix线程隔离&请求缓存&请求合并

    接着上一篇的Hystrix进行进一步了解. 当系统用户不断增长时,每个微服务需要承受的并发压力也越来越大,在分布式环境中,通常压力来自对依赖服务的调用,因为亲戚依赖服务的资源需要通过通信来实现,这样的 ...

  2. SpringCloud实战4-Hystrix线程隔离&请求缓存&请求合并

    接着上一篇的Hystrix进行进一步了解. 当系统用户不断增长时,每个微服务需要承受的并发压力也越来越大,在分布式环境中,通常压力来自对依赖服务的调用,因为亲戚依赖服务的资源需要通过通信来实现,这样的 ...

  3. 第六十二篇、AFN3.0封装网络请求框架,支持缓存

    1.网络请求 第一种实现方式: 功能:GET POST 请求 缓存逻辑: 1.是否要刷新本地缓存,不需要就直接发起无缓存的网络请求,否则直接读取本地数据 2.需要刷新本地缓存,先读取本地数据,有就返回 ...

  4. Spring-cloud (八) Hystrix 请求缓存的使用

    前言: 最近忙着微服务项目的开发,脱更了半个月多,今天项目的初版已经完成,所以打算继续我们的微服务学习,由于Hystrix这一块东西好多,只好多拆分几篇文章写,对于一般对性能要求不是很高的项目中,可以 ...

  5. hystrix中request cache请求缓存

    有一个概念,叫做reqeust context,请求上下文,一般来说,在一个web应用中, 我们会在一个filter里面,对每一个请求都施加一个请求上下文,就是说,tomcat容器内,每一次请求,就是 ...

  6. Android Xutils框架HttpUtil Get请求缓存问题

    话说,今天和服务器开发人员小小的逗逼了一下,为啥呢? 话说今天有个"收藏产品"的请求接口,是get request的哦,我客户端写好接口后,点击"收藏按钮",返 ...

  7. hystrix源码之请求缓存

    HystrixRequestCache 请求缓存.内部是一个静态ConcurrentHashMap存储各个命令的缓存器,RequestCacheKey为key,HystrixRequestCache为 ...

  8. Hystrix-request cache(请求缓存)

    开启请求缓存 请求缓存在run()和construce()执行之前生效,所以可以有效减少不必要的线程开销.你可以通过实现getCachekey()方法来开启请求缓存. package org.hope ...

  9. Spring Cloud(Dalston.SR5)--Hystrix 断路器-合并请求

    在 Spring Cloud 中可以使用注解的方式来支持 Hystrix 的合并请求,缓存与合并请求功能需要先初始化请求上下文才能实现,因此,必须实现 javax.servlet.Filter 用于创 ...

随机推荐

  1. Good Bye 2016 - D

    题目链接:http://codeforces.com/contest/750/problem/D 题意:新年烟花爆炸后会往两端45°差分裂.分裂完后变成2部分,之后这2部分继续按这种规则分裂.现在给你 ...

  2. 安卓智能POS终端手持机PDA应用仓库出入库,移库,盘点,销售开单系统

    随着移动互联网的兴起,目前仓储管理所面临的的问题可以迎刃而解,WMS仓库系统解决方案通过智能终端扫描条码技术应用解决了工作量大导致工作效率不高,以及数据实时传输等问题,该方案主要提供仓库出入库,移库, ...

  3. 网站banner写法

    css .banner{ width: %; height: 375px; background: url(X.jpg) no-repeat center;} html <div class=& ...

  4. A*算法的原理 <转>

    第一部分:A*算法简介    写这篇文章的初衷是应一个网友的要求,当然我也发现现在有关人工智能的中文站点实在太少,我在这里 抛砖引玉,希望大家都来热心的参与.     还是说正题,我先拿A*算法开刀, ...

  5. BZOJ2506: calc

    Description            给一个长度为n的非负整数序列A1,A2,…,An.现有m个询问,每次询问给出l,r,p,k,问满足l<=i<=r且Ai mod p = k的值 ...

  6. MarkDown笔记

    MarkDown是一种轻量级的标记语言,可以比较简洁地格式化文本,所以比较方便地产生可读性良好的文档. 可以使用Markdown: 整理知识,学习笔记 发布日记,杂文,所见所想 撰写发布技术文稿(代码 ...

  7. delay(和setTimeout()的区别

    近来几日在写游戏代码时,频繁会用到定时器,偶尔想到有个.delay()方法,用了几次发现两者效果相差很大,遂就仔细考究了一下两者的区别! 1. setTimeout函数是从页面开始的时候计算time的 ...

  8. python面试总结

    1.python的优势 1.1 python是一门胶水语言,能够结合各种语言 1.2 python是支持面向对象编程 1.3 python是完全开放源代码,有大量的技术支持文档, 1.4 可移植,py ...

  9. HTML5 audio与video标签实现视频播放,音频播放

    随着互联网的飞速发展以及HTML5的应用,越来越多的项目中用到video,audio当常用标签. <audio> 标签属性 <audio src="song.mp3&quo ...

  10. Ncut源码编译错误的解决方法

    NCut是一个比较老的开源代码了.所以在新的matlab的环境下老出各种bug. 经过自己的各种折腾,总结为一下几点: 1.保证matlab的mex是有C编译器可以用的,具体可以用 mex -setu ...