hystrix的降级和超时都已经写过了,接下来记录下hystrix的请求缓存功能。对于同一个ip的对同一个方法的请求,hystrix有请求缓存功能可以让服务更快的返回结果。
示例如下,首先调用controller中的方法,该方法调用缓存方法。从上下文中获得结果,记得用lombok的@Cleanup关闭上下文。
@RestController
public class Controller {
@Autowired
private MyService myService;
@Autowired
private RequestCacheService requestCacheService;
@GetMapping("/cache")
public Friend cache(String name){
// @Cleanup默认会调用context的close方法,也可以通过指定值来指定
@Cleanup HystrixRequestContext context = HystrixRequestContext.initializeContext();
Friend friend = requestCacheService.requestCache(name);
name += "!";
friend = requestCacheService.requestCache(name);
return friend;
}
}
@CacheResult可以打开请求缓存功能,当第二次访问时,对参数name值相同的请求,直接返回上下文中的结果,提高服务响应速度。
@Slf4j
@Service
public class RequestCacheService {
@Autowired
private MyService service;
@CacheResult
// commandKey的值对应application.yml里的服务名字"cacheKey",简化方法签名
@HystrixCommand(commandKey = "cacheKey")
public Friend requestCache(@CacheKey String name){
log.info("request cache " + name);
Friend friend = new Friend();
friend.setName(name);
friend = service.sayHiPost(friend);
log.info("after requesting cache " + name);
return friend;
}
}