image.png
实现步骤如下
1.在下面创建RequestCacheService类
要点:
@CacheResult 把Friend 对象缓存起来
@CacheKey 唯一标识,把name当做获取Friend的唯一的key
@HystrixCommand 针对一个特定的服务要进行降级
- @HystrixCommand(commandKey = "cacheKey") 超时配置(简化Hystrix超时配置),
如:hystrix.command.cacheKey.execution.isolation.thread.timeoutInMilliseconds=3000 //MyService#retry(int) - @HystrixCommand(commandKey = "fallbackMethod"),创建单独的降级方法,但是方法的参数必须和被注解的一致
RequestCacheService:
package com.imooc.springcloud.hystrix;
import com.imooc.springcloud.Friend;
import com.imooc.springcloud.MyService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by 半仙.
*/
@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;
}
}
2.调用RequestCacheService类中的requestCache方法
save的时候一直点击保存,RequestCacheService上下文可以让方法只被调用一次
- @Cleanup 使用 帮忙调用上下文的close方法,可不用try cache了 @Cleanup(“value”)?
package com.imooc.springcloud;
import com.imooc.springcloud.hystrix.RequestCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
@Autowired
private MyService myService;
@Autowired
private RequestCacheService requestCacheService;
@GetMapping("/fallback")
public String fallback(){
return myService.error();
}
@GetMapping("/timeout")
public String timeout(Integer timeout){
return myService.retry(timeout);
}
@GetMapping("/cache")
public Friend cache(String name){
Friend friend = requestCacheService.requestCache(name);
return friend;
}
}
3.配置文件
image.png
4.测试缓存
image.png
image.png
121?
1个上线文
2个注解@CacheResult @CacheKey
1个@HystrixCommand








网友评论