使用 HystrixCommand 和cache注解 怎么保证cache取到的不是fallbackMethod返回的值
时间: 2023-12-08 11:06:03 浏览: 39
使用 HystrixCommand 和 cache 注解时,可以通过以下几个步骤来保证 cache 取到的不是 fallbackMethod 返回的值:
1. 在 HystrixCommand 注解中设置 cacheKeyMethod 属性,该属性指定了生成缓存 key 的方法。确保该方法返回的 key 与 fallbackMethod 方法返回的 key 不同。
2. 在 fallbackMethod 方法中不要使用缓存,直接调用远程服务获取最新数据。
3. 在 HystrixCommand 注解中设置 cacheEnabled 属性为 false,禁用缓存。
4. 在 fallbackMethod 方法中将数据写入缓存,确保下次请求时能够从缓存中获取到最新数据。
示例代码如下:
```
@HystrixCommand(fallbackMethod = "fallbackMethod", cacheKeyMethod = "getCacheKey", cacheEnabled = false)
public Object getData() {
// 从缓存中获取数据
Object data = cache.get(key);
if (data != null) {
return data;
}
// 获取最新数据
data = remoteService.getData();
// 将数据写入缓存
cache.put(key, data);
return data;
}
public Object fallbackMethod() {
// 直接调用远程服务获取最新数据
Object data = remoteService.getData();
// 将数据写入缓存
cache.put(key, data);
return data;
}
public String getCacheKey() {
// 生成缓存 key
return key + "_data";
}
```
在上面的示例代码中,我们通过设置 cacheKeyMethod 属性来生成缓存 key,并在 fallbackMethod 方法中直接调用远程服务获取最新数据。同时,我们禁用了缓存,并在 fallbackMethod 方法中将数据写入缓存,确保下次请求时能够从缓存中获取到最新数据。