|
| 1 | +package cn.iocoder.springcloud.labx23.hystrixdemo.service; |
| 2 | + |
| 3 | +import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; |
| 4 | +import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove; |
| 5 | +import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult; |
| 6 | +import org.apache.commons.lang.exception.ExceptionUtils; |
| 7 | +import org.slf4j.Logger; |
| 8 | +import org.slf4j.LoggerFactory; |
| 9 | +import org.springframework.beans.factory.annotation.Autowired; |
| 10 | +import org.springframework.stereotype.Service; |
| 11 | +import org.springframework.web.client.RestTemplate; |
| 12 | + |
| 13 | +@Service |
| 14 | +public class CacheDemoService { |
| 15 | + |
| 16 | + private Logger logger = LoggerFactory.getLogger(CacheDemoService.class); |
| 17 | + |
| 18 | + @Autowired |
| 19 | + private RestTemplate restTemplate; |
| 20 | + |
| 21 | + @HystrixCommand(fallbackMethod = "getUserFallback") |
| 22 | + @CacheResult(cacheKeyMethod = "genGetUserCacheKey") |
| 23 | + public String getUser(Integer id) { |
| 24 | + logger.info("[getUser][准备调用 user-service 获取用户({})详情]", id); |
| 25 | + return restTemplate.getForEntity("http://127.0.0.1:18080/user/get?id=" + id, String.class).getBody(); |
| 26 | + } |
| 27 | + |
| 28 | + @HystrixCommand |
| 29 | + @CacheRemove(commandKey = "getUser", cacheKeyMethod = "genGetUserCacheKey") |
| 30 | + public void updateUser(Integer id) { |
| 31 | + logger.info("[updateUser][更新用户({})详情]", id); |
| 32 | + } |
| 33 | + |
| 34 | + public String getUserFallback(Integer id, Throwable throwable) { |
| 35 | + logger.info("[getUserFallback][id({}) exception({})]", id, ExceptionUtils.getRootCauseMessage(throwable)); |
| 36 | + return "mock:User:" + id; |
| 37 | + } |
| 38 | + |
| 39 | + public String genGetUserCacheKey(Integer id) { |
| 40 | + return "USER_" + id; |
| 41 | + } |
| 42 | + |
| 43 | +} |
0 commit comments