在 Spring Cloud 中可以使用注解的方式来支持 Hystrix 的缓存,缓存与合并请求功能需要先初始化请求上下文才能实现,因此,必须实现 javax.servlet.Filter 用于创建和销毁 Hystrix 的请求上下文,而缓存的注解有 @CacheResult、@CacheRemove,@CacheResult 注解必须和 @HystrixCommand 注解一起使用,示例如下:

  • 创建 Filter

    在 Filter 初始化时就创建 HystrixRequestContext,然后在每个请求调用 doFilter 方法时,将初始化的上下文赋值到当前线程存储,这样就能在全局使用 Hystrix 的缓存和合并请求

    package org.lixue;

     
     

    import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;

     
     

    import javax.servlet.*;

    import javax.servlet.annotation.WebFilter;

    importj ava.io.IOException;

     
     

    @WebFilter(urlPatterns="/*",filterName="HystrixRequestContextFilter")

    public class HystrixRequestContextFilter implements Filter{

    HystrixRequestContext context=null;

     
     

    @Override

    public void init(FilterConfig filterConfig) throws ServletException{

    context=HystrixRequestContext.initializeContext();

    }

     
     

    @Override

    publicvoid doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException{

    HystrixRequestContext.setContextOnCurrentThread(context);

    try{

    chain.doFilter(request,response);

    }catch(Exceptionex){

    ex.printStackTrace();

    }

    }

     
     

    @Override

    publicvoiddestroy(){

    if(context!=null){

    context.shutdown();

    }

    }

    }

     
     

  • 创建服务调用

    注解 @CacheResult 必须和 @HystrixCommand 同时使用,@CacheResult 注解的 cacheKeyMethod 参数指定的方法必须和 @CacheResult 标注的方法参数一致,并且相同参数产生的 key 值应该一致;

    如果数据存在修改,则必须使用 @CacheRemove 注解标注修改方法,同样也需要指定 cacheKeyMethod 参数,表示需要移除缓存的 key,其 commandKey 参数也必须指定和 @HystrixCommand 注解的 commandKey 值一致;

    如果不指定 @CacheResult 和 @CacheRemove 注解的 cacheKeyMethod 参数,也可使用 @CacheKey 注解来标注方法的参数,表示使用方法的参数来作为缓存 key

    package org.lixue;

     
     

    import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

    import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;

    import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;

    import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;

    import org.springframework.beans.factory.annotation.Autowired;

    import org.springframework.stereotype.Component;

    import org.springframework.web.client.RestTemplate;

     
     

    @Component

    public class HelloWorldClient{

     
     

    @Autowired

    private RestTemplate restTemplate;

     
     

    @HystrixCommand(fallbackMethod="speakFallback",commandKey="hello-world",

    threadPoolKey="hello-world",groupKey="hello-world",

    commandProperties={

    @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="500")

    },

    threadPoolProperties={

    @HystrixProperty(name="coreSize",value="50")

    }

    )

    @CacheResult(cacheKeyMethod="speakCacheKey")

    public String speak(String name){

    if(name==null||"".equals(name)){

    name="null";

    }

    return restTemplate.getForObject("http://HELLOWORLD-PROVIDER/speaks?names="+name,String.class);

    }

     
     

    /**

    *生成speak方法的缓存Key

    *

    *@param name

    *@return

    */

    private String speakCacheKey(String name){

    return"speak."+name;

    }

     
     

    /**

    *修改speak数据,移除缓存

    *

    *@param name

    *@return

    */

    @CacheRemove(commandKey="hello-world",cacheKeyMethod="speakCacheKey")

    public String updateSpeak(String name){

    return name;

    }

     
     

    /**

    *speak返回的回退方法

    *

    *@param name

    *@return

    */

    private String speakFallback(String name){

    return"call error,name is"+name;

    }

    }

  • 服务增加日志

    @RequestMapping(method=RequestMethod.GET,name="speak",path="/speaks",

    produces=MediaType.APPLICATION_JSON_UTF8_VALUE)

    public Map<String,String> speaks(@RequestParam(value="names")String names) throws InterruptedException{

    System.out.println("speaksnames="+names);

    Map<String,String>map=newHashMap<>();

    if(names==null||"".equals(names)){

    return map;

    }

     
     

    String[] splitName=names.split(",");

    for(Stringname:splitName){

    map.put(name,"HelloWorld"+name+"Port="+port);

    }

    return map;

    }

     
     

  • 测试验证

    由于我们使用了 Ribbon 因此首先启动 eureka-server 和 service-provider 服务,然后启动该项目,访问 http://localhost:8077/speak?name=abc 可以看到能正常返回信息,如下:

    {"abc":"Hello World abc Port=8002"}

    服务输出日志:

    speaks names=abc

    多次刷新,可以看到服务的日志只显示了一次,表示后续的刷新访问都是使用的 Hystrix 缓存。

     
     

     
     

     
     

Spring Cloud(Dalston.SR5)--Hystrix 断路器-缓存的更多相关文章

  1. Spring Cloud(Dalston.SR5)--Hystrix 断路器

    Spring Cloud 对 Hystrix 进行了封装,使用 Hystrix 是通过 @HystrixCommand 注解来使用的,被 @HystrixCommand 注解标注的方法,会使用 Asp ...

  2. Spring Cloud(Dalston.SR5)--Hystrix 断路器-合并请求

    在 Spring Cloud 中可以使用注解的方式来支持 Hystrix 的合并请求,缓存与合并请求功能需要先初始化请求上下文才能实现,因此,必须实现 javax.servlet.Filter 用于创 ...

  3. Spring Cloud(Dalston.SR5)--Hystrix 监控

    在服务调用者加入 Actuator ,可以对服务调用者的健康情况进行实时监控,例如,断路器是否打开.当前负载情况等. 服务调用者 需要增加 actuator依赖, 修改 POM.xml 中增加以下依赖 ...

  4. Spring Cloud入门教程-Hystrix断路器实现容错和降级

    简介 Spring cloud提供了Hystrix容错库用以在服务不可用时,对配置了断路器的方法实行降级策略,临时调用备用方法.这篇文章将创建一个产品微服务,注册到eureka服务注册中心,然后我们使 ...

  5. Spring Cloud(Dalston.SR5)--Feign 与 Hystrix 断路器整合

    创建项目 要使 Feign 与 Hystrix 进行整合,我们需要增加 Feign 和 Hystrix 的依赖,修改 POM.xml 中增加以下依赖项如下: <?xmlversion=" ...

  6. Spring Cloud(Dalston.SR5)--Config 集群配置中心-刷新配置

    远程 SVN 服务器上面的配置修改后,需要通知客户端来改变配置,需要增加 spring-boot-starter-actuator 依赖并将 management.security.enabled 设 ...

  7. Spring Cloud(Dalston.SR5)--Config 集群配置中心

    Spring Cloud Config 是一个全新的项目,用来为分布式系统中的基础设施和微服务应用提供集中化的外部配置支持,他分为服务端和客户端两个部分.服务端也称为分布式配置中心,是一个独立的微服务 ...

  8. Spring Cloud(Dalston.SR5)--Feign 声明式REST客户端

    Spring Cloud 对 Feign 进行了封装,集成了 Ribbon 并结合 Eureka 可以实现客户端的负载均衡,Spring Cloud 实现的 Feign 客户端类名为 LoadBala ...

  9. Spring Cloud(Dalston.SR5)--Zuul 网关-微服务集群

    通过 url 映射的方式来实现 zuul 的转发有局限性,比如每增加一个服务就需要配置一条内容,另外后端的服务如果是动态来提供,就不能采用这种方案来配置了.实际上在实现微服务架构时,服务名与服务实例地 ...

随机推荐

  1. linux各种系统下载地址

    1.Arch Linux Arch Linux在安装过程中提供了强大的可定制选择,支持你下载和安装自己所需的程序包.虽然这个选择对新手来说没有多大的帮助,但是它确实能够帮助那些使用Arch构建系统和存 ...

  2. stack && queue

    package elementary_data_structure; import java.util.Iterator;import java.util.NoSuchElementException ...

  3. HDU 6140 17多校8 Hybrid Crystals(思维题)

    题目传送: Hybrid Crystals Problem Description > Kyber crystals, also called the living crystal or sim ...

  4. HDU 4704 Sum(隔板原理+组合数求和公式+费马小定理+快速幂)

    题目传送:http://acm.hdu.edu.cn/showproblem.php?pid=4704 Problem Description   Sample Input 2 Sample Outp ...

  5. python2和Python3的区别(长期更新)

    1.在Python2中无需将打印的内容放在括号内,但是Python3中必须将打印的内容放在括号内,从技术上看Python3中的print是函数. 2.对于用户交互终点额输入input,在python2 ...

  6. Ubuntu上latex+atom配置

    网上流传的latex+atom大都是windows上的,Ubuntu与windows上的配置方式大同小异,这里写下自己的经验: 分为三个步骤,首先安装texlive,texlive是latex的依赖库 ...

  7. C语言--第0次作业评分和总结(5班)

    作业链接http://www.cnblogs.com/ranh941/p/7496793.html 一.评分要求 *得分点1:建博客(5分) *得分点2:第0次作业(45分) **问题0:阅读推荐博客 ...

  8. sudo操作

    在非root权限下,无法执行 vim /etc/profile 并保存,提示如下错误: "profile" E212: Can't open file for writing Pr ...

  9. php基础-4

    require和include require和include都是导入外部php文件的方法,使用方法为require和include关键字后接导入包(php_file)的名字的字符串形式. 当导入的包 ...

  10. python------软件目录结构规范

    一. 目录结构 www.cnblogs.com/alex3714/articles/5765046.html print(__file__) 获得相对路径 import osprint(os.path ...