详解spring cloud hystrix缓存功能的使用

 更新时间:2018年08月18日 10:02:37   作者:TS笑天  
这篇文章主要介绍了详解spring cloudhystrix缓存功能的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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,否则程序无法找到缓存位置。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 详解Redis 缓存 + Spring 的集成示例

    详解Redis 缓存 + Spring 的集成示例

    本篇文章主要介绍了Redis 缓存 + Spring 的集成示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-04-04
  • 关于java.lang.NumberFormatException: null的问题及解决

    关于java.lang.NumberFormatException: null的问题及解决

    这篇文章主要介绍了关于java.lang.NumberFormatException: null的问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • springboot拦截器Interceptor的使用,你都了解吗

    springboot拦截器Interceptor的使用,你都了解吗

    springmvc 中的拦截器可以对请求进行判别,在请求到达控制器之前,把非法的请求给拦截掉下面来说一说, 它在springboot中的使用,感兴趣的朋友一起看看吧
    2021-07-07
  • springBoot快速访问工程目录下的静态资源

    springBoot快速访问工程目录下的静态资源

    springboot工程,是没有webapp文件夹的,静态文件放在src/main/resources/static文件夹下即可,模板文件放在src/main/resources/templates下,本文给大家介绍springBoot快速访问工程目录下的静态资源的相关知识,一起看看吧
    2021-06-06
  • SpringBoot中的@EnableConfigurationProperties注解详细解析

    SpringBoot中的@EnableConfigurationProperties注解详细解析

    这篇文章主要介绍了SpringBoot中的@EnableConfigurationProperties注解详细解析,如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component或者实现了@Component的其他注解,那么在IOC容器中是获取不到properties 配置文件转化的bean,需要的朋友可以参考下
    2024-01-01
  • Java Socket实现的传输对象功能示例

    Java Socket实现的传输对象功能示例

    这篇文章主要介绍了Java Socket实现的传输对象功能,结合具体实例形式分析了java socket传输对象的原理及接口、客户端、服务器端相关实现技巧,需要的朋友可以参考下
    2017-06-06
  • Maven插件的安装及使用

    Maven插件的安装及使用

    这篇文章主要介绍了Maven插件的安装及使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • 使用Java编写一个图片word互转工具

    使用Java编写一个图片word互转工具

    这篇文章主要介绍了使用Java编写一个PDF Word文件转换工具的相关资料,需要的朋友可以参考下
    2023-01-01
  • java底层JDK Logging日志模块处理细节深入分析

    java底层JDK Logging日志模块处理细节深入分析

    这篇文章主要为大家介绍了java底层JDK Logging日志模块处理细节深入分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-03-03
  • java中gc算法实例用法

    java中gc算法实例用法

    在本篇文章里小编给大家整理了一篇关于java中gc算法实例用法,有兴趣的朋友们可以参考学习下。
    2021-01-01

最新评论