一次controller调用中,多次调用service
@GetMapping("/cache-annotation-01")
public List<ServiceInstance> useCacheByAnnotation01(@RequestParam String serviceId) {
log.info("use cache by annotation01(controller) to get nacos client info: [{}]",
serviceId);
List<ServiceInstance> result01 =
cacheHystrixCommandAnnotation.useCacheByAnnotation01(serviceId);
List<ServiceInstance> result02 =
cacheHystrixCommandAnnotation.useCacheByAnnotation01(serviceId);
// 清除掉缓存
cacheHystrixCommandAnnotation.flushCacheByAnnotation01(serviceId);
List<ServiceInstance> result03 =
cacheHystrixCommandAnnotation.useCacheByAnnotation01(serviceId);
// 这里有第四次调用
return cacheHystrixCommandAnnotation.useCacheByAnnotation01(serviceId);
}
第一种 Hystrix Cache 注解的使用方法,手动getCacheKey→
@CacheResult(cacheKeyMethod = “getCacheKey”)
@HystrixCommand(commandKey = “类名”)
第二种 Hystrix Cache 注解的使用方法,常用,
@CacheResult
@HystrixCommand(commandKey = “类名”)
参数加@CacheKey
第三种 Hystrix Cache 注解的使用方法,省略@CacheKey
/**
* <h1>使用注解方式开启 Hystrix 请求缓存</h1>
* */
@Slf4j
@Service
public class CacheHystrixCommandAnnotation {
private final NacosClientService nacosClientService;
public CacheHystrixCommandAnnotation(NacosClientService nacosClientService) {
this.nacosClientService = nacosClientService;
}
// 第一种 Hystrix Cache 注解的使用方法
@CacheResult(cacheKeyMethod = "getCacheKey")
@HystrixCommand(commandKey = "CacheHystrixCommandAnnotation")
public List<ServiceInstance> useCacheByAnnotation01(String serviceId) {
log.info("use cache01 to get nacos client info: [{}]", serviceId);
return nacosClientService.getNacosClientInfo(serviceId);
}
@CacheRemove(commandKey = "CacheHystrixCommandAnnotation",
cacheKeyMethod = "getCacheKey")
@HystrixCommand
public void flushCacheByAnnotation01(String cacheId) {
log.info("flush hystrix cache key: [{}]", cacheId);
}
public String getCacheKey(String cacheId) {
return cacheId;
}
// 第二种 Hystrix Cache 注解的使用方法
@CacheResult
@HystrixCommand(commandKey = "CacheHystrixCommandAnnotation")
public List<ServiceInstance> useCacheByAnnotation02(@CacheKey String serviceId) {
log.info("use cache02 to get nacos client info: [{}]", serviceId);
return nacosClientService.getNacosClientInfo(serviceId);
}
@CacheRemove(commandKey = "CacheHystrixCommandAnnotation")
@HystrixCommand
public void flushCacheByAnnotation02(@CacheKey String cacheId) {
log.info("flush hystrix cache key: [{}]", cacheId);
}
// 第三种 Hystrix Cache 注解的使用方法
@CacheResult
@HystrixCommand(commandKey = "CacheHystrixCommandAnnotation")
public List<ServiceInstance> useCacheByAnnotation03(String serviceId) {
log.info("use cache03 to get nacos client info: [{}]", serviceId);
return nacosClientService.getNacosClientInfo(serviceId);
}
@CacheRemove(commandKey = "CacheHystrixCommandAnnotation")
@HystrixCommand
public void flushCacheByAnnotation03(String cacheId) {
log.info("flush hystrix cache key: [{}]", cacheId);
}
}