Hystrix實現Request Cache減壓
阿新 • • 發佈:2021-01-01
技術標籤:微服務
本篇配置類及其他程式碼可參考《Hystrix使用fallback完成消費降級》
我們在Hystrix下新建一個CacheService
@Slf4j
@Service
public class RequestCacheService {
@Autowired
private MyService service;
@CacheResult
@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;
}
}
建立一個測試Controller,在這裡我們嘗試呼叫兩次requestCache()
@GetMapping("/cache")
publicFriend cache(String name) {
@Cleanup HystrixRequestContext context = HystrixRequestContext.initializeContext();
Friend friend = requestCacheService.requestCache(name);
friend = requestCacheService.requestCache(name);
return friend;
}
啟動專案,我們呼叫localhost:50000/cache?name=王老五
可以看到Feign的日誌中,只觸發了一次呼叫
我們對
cache()
函式稍微做一點修改
@GetMapping("/cache")
publicFriend cache(String name) {
@Cleanup HystrixRequestContext context = HystrixRequestContext.initializeContext();
Friend friend = requestCacheService.requestCache(name);
name += "!";
friend = requestCacheService.requestCache(name);
return friend;
}
重啟專案,再次請求,這時候能看到Feign中觸發了兩次呼叫
說明@CacheKey
已經生效了,在傳入相同key時,觸發了Hystrix的快取!