麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 開發 > Java > 正文

詳解spring cloud hystrix緩存功能的使用

2024-07-14 08:42:03
字體:
來源:轉載
供稿:網友

hystrix緩存的作用是 

- 1.減少重復的請求數,降低依賴服務的返回數據始終保持一致。 
- 2.==在同一個用戶請求的上下文中,相同依賴服務的返回數據始終保持一致==。 
- 3.請求緩存在run()和construct()執行之前生效,所以可以有效減少不必要的線程開銷。

1 通過HystrixCommand類實現

1.1 開啟緩存功能

繼承HystrixCommand或HystrixObservableCommand,覆蓋getCacheKey()方法,指定緩存的key,開啟緩存配置。

import com.netflix.hystrix.HystrixCommand;import com.netflix.hystrix.HystrixCommandGroupKey;import com.netflix.hystrix.HystrixCommandKey;import com.netflix.hystrix.HystrixRequestCache;import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;import com.szss.demo.orders.vo.UserVO;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.client.RestTemplate;public class UserCacheCommand extends HystrixCommand<UserVO> {  private static final Logger LOGGER = LoggerFactory.getLogger(UserCacheCommand.class);  private static final HystrixCommandKey GETTER_KEY= HystrixCommandKey.Factory.asKey("CommandKey");  private RestTemplate restTemplate;  private String username;  public UserCacheCommand(RestTemplate restTemplate, String username) {    super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("userCacheCommand")).andCommandKey(GETTER_KEY));    this.restTemplate = restTemplate;    this.username = username;  }  @Override  protected UserVO run() throws Exception {    LOGGER.info("thread:" + Thread.currentThread().getName());    return restTemplate.getForObject("http://users-service/user/name/{username}", UserVO.class, username);  }  @Override  protected UserVO getFallback() {    UserVO user = new UserVO();    user.setId(-1L);    user.setUsername("調用失敗");    return user;  }  @Override  protected String getCacheKey() {    return username;  }  public static void flushCache(String username){    HystrixRequestCache.getInstance(GETTER_KEY, HystrixConcurrencyStrategyDefault.getInstance()).clear(username);  }}

1.2 配置HystrixRequestContextServletFilter

通過servlet的Filter配置hystrix的上下文。

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;import javax.servlet.*;import javax.servlet.annotation.WebFilter;import java.io.IOException;@WebFilter(filterName = "hystrixRequestContextServletFilter",urlPatterns = "/*",asyncSupported = true)public class HystrixRequestContextServletFilter implements Filter {  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {    HystrixRequestContext context = HystrixRequestContext.initializeContext();    try {      chain.doFilter(request, response);    } finally {      context.shutdown();    }  }  @Override  public void init(FilterConfig filterConfig) throws ServletException {  }  @Override  public void destroy() {  }}

在不同context中的緩存是不共享的,還有這個request內部一個ThreadLocal,所以request只能限于當前線程。

1.3 清除失效緩存

繼承HystrixCommand或HystrixObservableCommand,在更新接口調用完成后,清空緩存。

import com.netflix.hystrix.HystrixCommand;import com.netflix.hystrix.HystrixCommandGroupKey;import com.netflix.hystrix.HystrixCommandKey;import com.szss.demo.orders.vo.UserVO;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpEntity;import org.springframework.web.client.RestTemplate;public class UserUpdateCacheCommand extends HystrixCommand<UserVO> {  private static final Logger LOGGER = LoggerFactory.getLogger(UserUpdateCacheCommand.class);  private static final HystrixCommandKey GETTER_KEY = HystrixCommandKey.Factory.asKey("CommandKey");  private RestTemplate restTemplate;  private UserVO user;  public UserUpdateCacheCommand(RestTemplate restTemplate, UserVO user) {    super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("userUpdateCacheCommand")));    this.restTemplate = restTemplate;    this.user = user;  }  @Override  protected UserVO run() throws Exception {    LOGGER.info("thread:" + Thread.currentThread().getName());    HttpEntity<UserVO> u = new HttpEntity<UserVO>(user);    UserVO userVO=restTemplate.postForObject("http://users-service/user",u,UserVO.class);    UserCacheCommand.flushCache(user.getUsername());    return userVO;  }//  @Override//  protected UserVO getFallback() {//    UserVO user = new UserVO();//    user.setId(-1L);//    user.setUsername("調用失敗");//    return user;//  }  @Override  protected String getCacheKey() {    return user.getUsername();  }}

2 使用@CacheResult、@CacheRemove和@CacheKey標注來實現緩存

2.1 使用@CacheResult實現緩存功能

  @CacheResult(cacheKeyMethod = "getCacheKey")  @HystrixCommand(commandKey = "findUserById", groupKey = "UserService", threadPoolKey = "userServiceThreadPool")  public UserVO findById(Long id) {    ResponseEntity<UserVO> user = restTemplate.getForEntity("http://users-service/user?id={id}", UserVO.class, id);    return user.getBody();  }  public String getCacheKey(Long id) {    return String.valueOf(id);  }

@CacheResult注解中的cacheKeyMethod用來標示緩存key(cacheKey)的生成函數。函數的名稱可任意取名,入參和標注@CacheResult的方法是一致的,返回類型是String。

2.2 使用@CacheResult和@CacheKey實現緩存功能

  @CacheResult  @HystrixCommand(commandKey = "findUserById", groupKey = "UserService", threadPoolKey = "userServiceThreadPool")  public UserVO findById2(@CacheKey("id") Long id) {    ResponseEntity<UserVO> user = restTemplate.getForEntity("http://users-service/user?id={id}", UserVO.class, id);    return user.getBody();  }

標注@HystrixCommand注解的方法,使用@CacheKey標注需要指定的參數作為緩存key。

2.3 使用@CacheRemove清空緩存

  @CacheRemove(commandKey = "findUserById")  @HystrixCommand(commandKey = "updateUser",groupKey = "UserService",threadPoolKey = "userServiceThreadPool")  public void updateUser(@CacheKey("id")UserVO user){    restTemplate.postForObject("http://users-service/user",user,UserVO.class);  }

@CacheRemove必須指定commandKey,否則程序無法找到緩存位置。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 日韩视频高清 | 亚洲欧美国产高清 | 视频一区二区不卡 | 一级一级一级一级毛片 | 久久手机在线视频 | 99国产精品国产免费观看 | 欧美日韩一区,二区,三区,久久精品 | 久久久噜噜噜久久熟有声小说 | 全免费午夜一级毛片真人 | 免费网站看毛片 | 国产在线中文 | 成人精品久久久 | 欧美交在线 | 国产精品久久久久久久av三级 | 国产一区二区在线观看视频 | 操操插插 | 一级毛片免费高清 | 精品视频 久久久 | 国产妇女乱码一区二区三区 | 青青国产在线视频 | 羞羞色在线观看 | 香蕉久草在线 | 久久伊人精品热在75 | 黄视频网址| 一级免费黄色 | 超碰97最新 | h视频在线免费观看 | 黄网站在线播放视频免费观看 | 国产免费激情视频 | 黄色网址进入 | 在线观看免费污视频 | 久久精品欧美一区二区三区不卡 | 成年人视频免费 | 中文字幕在线观看视频www | 日韩激情一区二区三区 | 国产日本在线 | 国产1区2区3区在线观看 | 一本色道久久综合狠狠躁篇适合什么人看 | 北原夏美av| 国产一级一区二区三区 | 黄色影院网站 |