5Hystrix 结果缓存 · SpringCloud微服务实战 · 看云

5. Hystrix 结果缓存

导航

缓存的在开发中经常被使用,不管是本地缓存、Redis缓存、Guava、ECache、MemCache等第三方缓存,在目前的目分布式系统中,尤其是对并发要求高的系统,缓存所占的地位非常重要。

本节代码地址


hystrix支持将一个请求结果缓存起来,下一个具有相同key的请求将直接从缓存中取出结果,减少请求开销。要使用hystrix cache功能

  1. 重写getCacheKey(),用来构造cache key;
  2. 构建context,如果请求B要用到请求A的结果缓存,A和B必须同处一个context。
    通过HystrixRequestContext.initializeContext()context.shutdown()可以构建一个context,这两条语句间的所有请求都处于同一个context。

5.1 新建FwHystrixCommondCache类

这里面我们重写了getCacheKey()方法,并已穿进去的参数作为缓存的key,我在run()方法中加了一个log日志,方便看到run()方法被调用到了几次


@Slf4j
public class FwHystrixCommondCache extends HystrixCommand<String> {
    private final String name;
    protected FwHystrixCommondCache(String name) {
        super(HystrixCommandGroupKey.Factory.asKey("myGrop"));
        this.name=name;
    }

    @Override
    protected String run(){
        log.info("get data,{}",this.name);
        return this.name+":"+Thread.currentThread().getName();
    }

    @Override
    protected String getCacheKey() {
        return this.name;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        for (int i = 0; i <5 ; i++) {
            FwHystrixCommondCache test = new FwHystrixCommondCache("test");
            log.info(test.execute());
        }
        context.shutdown();
    }
}

5.2 运行main方法

可以看到run()方法只被执行了一次

14:14:47.847 [hystrix-myGrop-1] INFO com.yisu.hystrix.without.FwHystrixCommondCache - get data,test
14:14:47.851 [main] INFO com.yisu.hystrix.without.FwHystrixCommondCache - test:hystrix-myGrop-1
14:14:47.858 [main] INFO com.yisu.hystrix.without.FwHystrixCommondCache - test:hystrix-myGrop-1
14:14:47.858 [main] INFO com.yisu.hystrix.without.FwHystrixCommondCache - test:hystrix-myGrop-1
14:14:47.859 [main] INFO com.yisu.hystrix.without.FwHystrixCommondCache - test:hystrix-myGrop-1
14:14:47.859 [main] INFO com.yisu.hystrix.without.FwHystrixCommondCache - test:hystrix-myGrop-1

设置了缓存之后,怎么清理缓存呢?请继续往后看