java - Hystrix 请求缓存示例

标签 java caching fault-tolerance hystrix

我想知道如何 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 a HystrixCommand 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/

相关文章:

java - WLP MicroProfile (FaultTolerance) 超时实现不会中断线程?

Java客户端-服务器套接字,重用客户端套接字抛出 "java.io.StreamCorruptedException: invalid type code: AC"

java - 我应该在方法中捕获这个 NumberFormatException 吗?

html - 为什么我的缓存 webapp 没有在第一次尝试时刷新更改?

rabbitmq - 服务器重启后自动重新连接到 RabbitMQ 集群

fault - 软件容错

JavaFX Circle 和 ImageView

java - Android Play 商店订阅计费不会触发任何操作

javascript - 当使用 javascript 更改时,浏览器是否缓存图像 src

javascript - 如何在 JQuery 中使用 localStorage 为 ajax 调用创建自定义缓存机制?