企业级java springcloud b2bc商城系统开源源码二次开发-hystrix 请求缓存

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

需要JAVA Spring Cloud大型企业分布式微服务云构建的B2B2C电子商务平台源码请加企鹅求求 :二一四七七七五六三三

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时,此方法的缓存将删除。

java springboot b2b2c shop 多用户商城系统源码

猜你喜欢

转载自blog.csdn.net/sinat_23107883/article/details/85069834