亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2018年08月18日 10:02:37   作者:TS笑天  
這篇文章主要介紹了詳解spring cloudhystrix緩存功能的使用,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

hystrix緩存的作用是

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

1 通過(guò)HystrixCommand類實(shí)現(xiàn)

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("調(diào)用失敗");
    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

通過(guò)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中的緩存是不共享的,還有這個(gè)request內(nèi)部一個(gè)ThreadLocal,所以request只能限于當(dāng)前線程。

1.3 清除失效緩存

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

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("調(diào)用失敗");
//    return user;
//  }

  @Override
  protected String getCacheKey() {
    return user.getUsername();
  }
}

2 使用@CacheResult、@CacheRemove和@CacheKey標(biāo)注來(lái)實(shí)現(xiàn)緩存

2.1 使用@CacheResult實(shí)現(xiàn)緩存功能

  @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用來(lái)標(biāo)示緩存key(cacheKey)的生成函數(shù)。函數(shù)的名稱可任意取名,入?yún)⒑蜆?biāo)注@CacheResult的方法是一致的,返回類型是String。

2.2 使用@CacheResult和@CacheKey實(shí)現(xiàn)緩存功能

  @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();
  }

標(biāo)注@HystrixCommand注解的方法,使用@CacheKey標(biāo)注需要指定的參數(shù)作為緩存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,否則程序無(wú)法找到緩存位置。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • java讀取用戶登入退出日志信息上傳服務(wù)端

    java讀取用戶登入退出日志信息上傳服務(wù)端

    這篇文章主要介紹了java讀取用戶登入退出日志信息上傳服務(wù)端的相關(guān)資料,需要的朋友可以參考下
    2016-05-05
  • Java的Spring框架下的AOP編程模式示例

    Java的Spring框架下的AOP編程模式示例

    這篇文章主要介紹了Java的Spring框架下的AOP編程模式示例,文中分別講到了基于XML和基于@AspectJ的自定義方式,需要的朋友可以參考下
    2015-12-12
  • 淺談synchronized加鎖this和class的區(qū)別

    淺談synchronized加鎖this和class的區(qū)別

    synchronized 是 Java 語(yǔ)言中處理并發(fā)問(wèn)題的一種常用手段,本文主要介紹了synchronized加鎖this和class的區(qū)別,具有一定的參考價(jià)值,感興趣的可以了解一下
    2021-11-11
  • 分析ThreadLocal內(nèi)存泄漏問(wèn)題

    分析ThreadLocal內(nèi)存泄漏問(wèn)題

    ThreadLocal的作用是提供線程內(nèi)的局部變量,這種變量在線程生命周期內(nèi)起作用,減少同一個(gè)線程內(nèi)多個(gè)函數(shù)或者組件之間一些公共變量傳遞的復(fù)雜度,但是如果濫用ThreadLocal可能會(huì)導(dǎo)致內(nèi)存泄漏,所以本文將為大家分析ThreadLocal內(nèi)存泄漏問(wèn)題
    2023-07-07
  • Java調(diào)用python代碼的五種方式總結(jié)

    Java調(diào)用python代碼的五種方式總結(jié)

    這篇文章主要給大家介紹了關(guān)于Java調(diào)用python代碼的五種方式,在Java中調(diào)用Python函數(shù)的方法有很多種,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-09-09
  • 關(guān)于bigDecimal類的精度保留方法

    關(guān)于bigDecimal類的精度保留方法

    這篇文章主要介紹了關(guān)于bigDecimal類的精度保留方法,計(jì)算機(jī)存儲(chǔ)的浮點(diǎn)數(shù)受存儲(chǔ)bit位數(shù)影響,只能保證一定范圍內(nèi)精準(zhǔn),超過(guò)bit范圍的只能取近似值,Java使用java.math.BigDecimal專門處理小數(shù)精度,需要的朋友可以參考下
    2023-07-07
  • SpringSecurity 手機(jī)號(hào)登錄功能實(shí)現(xiàn)

    SpringSecurity 手機(jī)號(hào)登錄功能實(shí)現(xiàn)

    這篇文章主要介紹了SpringSecurity 手機(jī)號(hào)登錄功能實(shí)現(xiàn),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧
    2023-12-12
  • JDK10中的局部變量類型推斷var

    JDK10中的局部變量類型推斷var

    這篇文章主要介紹了JDK10中的局部變量類型推斷var,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-09-09
  • mall整合SpringTask實(shí)現(xiàn)定時(shí)任務(wù)的方法示例

    mall整合SpringTask實(shí)現(xiàn)定時(shí)任務(wù)的方法示例

    這篇文章主要介紹了mall整合SpringTask實(shí)現(xiàn)定時(shí)任務(wù)的方法示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-06-06
  • SpringBoot如何自定義線程池配置類

    SpringBoot如何自定義線程池配置類

    有時(shí)候我們?cè)陧?xiàng)目中做一些長(zhǎng)鏈路的跑批任務(wù)時(shí),基于Springboot項(xiàng)目的定時(shí)任務(wù),我們可以指定一個(gè)自定義的線程配置類進(jìn)行單獨(dú)提供給具體跑批任務(wù)使用,而不占用整個(gè)系統(tǒng)資源,這篇文章主要介紹了SpringBoot如何自定義線程池配置類,需要的朋友可以參考下
    2024-04-04

最新評(píng)論