Hystrix请求缓存示例

IAm*_*aja 8 java caching fault-tolerance hystrix

我试图找出Hystrix如何请求缓存工作,但我没有关注他们在他们的文档中提供的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我觉得我在这里反对.我相信 Hystrix提供内置缓存,正如' cacheKey'所证明的那样,但我找不到任何可行的例子.我不想在这里重新发明轮子,如果已经提供了开箱即用的东西,我可以在我的命令中构建缓存.

所以我问:Hystrix(确切地说)请求缓存是什么样的?如何将条目添加到缓存中?如何/何时刷新缓存?它是可配置的(到期,最大尺寸等)吗?

Ell*_*sch 7

根据您链接到此处的文档,

通过getCacheKey()在HystrixCommand对象上实现该方法来启用请求缓存...

你还没有实现getCacheKey(),

@Override
protected String getCacheKey() {
    return String.valueOf(id); // <-- changed from `value` in example
}
Run Code Online (Sandbox Code Playgroud)

那你还需要一个 HystrixRequestContext

HystrixRequestContext context = HystrixRequestContext.initializeContext();
Run Code Online (Sandbox Code Playgroud)

这是(再次,根据文件)

通常,此上下文将通过ServletFilter包装用户请求或其他生命周期挂钩进行初始化和关闭.

然后我相信你不能改变那样的方法签名execute()(doExecute()不是接口的一部分),而是你将参数传递给你的命令构造函数,并请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.
Run Code Online (Sandbox Code Playgroud)