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

这篇文章主要介绍了详解spring cloud hystrix请求缓存(request cache),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

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

以上就是详解spring cloud hystrix请求缓存(request cache)的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java