栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

详解spring cloud hystrix请求缓存(request cache)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

详解spring cloud hystrix请求缓存(request cache)

hystrix支持将一个请求结果缓存起来,下一个具有相同key的请求将直接从缓存中取出结果,减少请求开销。要使用该功能必须管理HystrixRequestContext,如果请求B要用到请求A的结果缓存,A和B必须同处一个context。通过HystrixRequestContext.initializeContext()和context.shutdown()可以构建一个context,这两条语句间的所有请求都处于同一个context,当然这个管理过程可以通过自定义的filter来实现,参考上一篇文章https://www.jb51.net/article/140527.htm

Hystrix请求缓存注解

@CacheResult 加入该注解的方法将开启请求缓存,默认情况下该方法的所有参数作为缓存的key,也就是说只有该方法的所有参数都一致时才会走缓存。

@Service
public class UserCacheService {
  @Autowired
  private UserFeignClient userFeignClient;

  
  @CacheResult
  @HystrixCommand(commandProperties = {
      @HystrixProperty(name="requestCache.enabled",value = "true")
  })
  public User findUserById(Integer id){
    return userFeignClient.findUserById(id);
  }
}

如果requestCache.enabled设置为false,即使加了@CacheResult,缓存也不起作用。

@CacheKey 通过该注解可以指定缓存的key

 @CacheResult
  @HystrixCommand(commandProperties = {
      @HystrixProperty(name="requestCache.enabled",value = "true")
  })
  public User findUserByIdAndName(@CacheKey Integer id,String name){
    return userFeignClient.findUserById(id);
  }

上面的代码我们用@CacheKey修饰了id字段,说明只要id相同的请求默认都会走缓存,与name字段无关,如果我们指定了@CacheResult的cacheKeyMethod属性,则@CacheKey注解无效

@CacheRemove 该注解的作用就是使缓存失效


  @CacheResult
  @CacheRemove(commandKey = "findUserById")
  @HystrixCommand(commandProperties = {
      @HystrixProperty(name="requestCache.enabled",value = "true")
  })
  public User findUserByIdAndName2(@CacheKey Integer id,String name){
    return userFeignClient.findUserById(id);
  }

以上代码指定了@CacheRemove的属性commandKey的值为findUserById,作用就是当调用findUserById时,此方法的缓存将删除。

完整版代码请参考:https://github.com/jingangwang/micro-service

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/140838.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号