我想知道如何 Hystrix request caching有效,但我没有遵循他们在文档中提供的 wiki 或端到端示例。
基本上我有以下 HystrixCommand
子类:
public class GetFizzCommand extends HystrixCommand<Fizz> {
private Long id;
private Map<Long,Fizz> fizzCache = new HashMap<Long,Fizz>();
void doExecute(Long id) {
this.id = id;
execute();
}
@Override
public Fizz run() {
return getFizzSomehow();
}
@Override
public Fizz getFallback() {
// Consult a cache somehow.
// Perhaps something like a Map<Long,Fizz> where the 'id' is the key (?)
// If the 'id' exists in the cache, return it. Otherwise, give up and return
// NULL.
fizzCache.get(id);
}
}
所以我觉得我在这里违背了原则。我相信 Hystrix 提供内置缓存,'cacheKey
' 证明了这一点,但我找不到任何有效的例子。如果开箱即用,我不想在这里重新发明轮子并在我的命令中构建缓存。
所以我问:Hystrix 的请求缓存是什么样的(确切地说)?条目如何添加到缓存中?如何/何时刷新缓存?它是否可配置(过期时间、最大尺寸等)?
最佳答案
根据您链接到 here 的文档,
Request caching is enabled by implementing the
getCacheKey()
method on aHystrixCommand
object...
你还没有实现 getCacheKey()
,
@Override
protected String getCacheKey() {
return String.valueOf(id); // <-- changed from `value` in example
}
然后你还需要一个 HystrixRequestContext
HystrixRequestContext context = HystrixRequestContext.initializeContext();
这是(同样,根据文档)
Typically this context will be initialized and shutdown via a
ServletFilter
that wraps a user request or some other lifecycle hook.
那我相信你不能改变 execute()
的方法签名像那样( doExecute()
不是接口(interface)的一部分)而是将参数传递给命令构造函数并请注释 execute
用@Override
所以如果你忘记了然后你会得到一个编译器错误
HystrixRequestContext context = HystrixRequestContext.initializeContext();
GetFizzCommand commandA = new GetFizzCommand(2L);
GetFizzCommand commandB = new GetFizzCommand(2L);
Fizz a = commandA.execute(); // <-- should not be cached
Fizz b = commandB.execute(); // <-- should be cached.
关于java - Hystrix 请求缓存示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27117065/