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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

乃刀的青春   2021-03-31 我要评论

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

Hystrix请求缓存注解

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

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

  /**
   * @HystrixCommand 的requestCache.enabled 可控制是否支持缓存
   * 只有加了@CacheResult才能缓存,即使requestCache.enabled=true
   * @param id  用户id
   * @return 指定的用户
   */
  @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 该注解的作用就是使缓存失效

/**
   * 通过@CacheRemove 注解指定当调用findUserById时将此方法的缓存删除
   * @param id  用户id
   * @param name 用户姓名
   * @return 指定的用户
   */
  @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

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们