(Forty-three) java version of spring cloud micro Services Architecture b2b2c e-commerce platform -hystrix request cache

hystrix support request cache the result, the next request will be taken with the same key results directly from the cache, the request to reduce overhead. To use this feature must manage HystrixRequestContext, if the request is a request B to use the cached results of A, A and B must be at a same context. Can build a context by HystrixRequestContext.initializeContext () and context.shutdown (), all requests between these two statements are in the same context, of course, this management process can be done by a custom filter.

Hystrix request caching annotation
method @CacheResult join the annotation request will open the cache, by default all the parameters in the case of this method as a cache key, the cache will go only when that is all the parameters of the method are the same.

@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);
    }
}

If requestCache.enabled set to false, even if the addition of @CacheResult, the cache does not work.

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

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

The above code we use @CacheKey modify the id field, id request demonstrates that if the same default cache will go, nothing to do with the name field, if we specify cacheKeyMethod property @CacheResult, the @CacheKey comment is invalid

@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);
    }

The above code specifies the property value commandKey of @CacheRemove findUserById, the role is when you call findUserById, this method will delete the cache.

Guess you like

Origin blog.csdn.net/vvx0206/article/details/95164933