Hystrix熔断机制就像家里的保险丝一样,若同时使用高功率的电器,就会烧坏电路,这时候保险丝自动断开就有效的保护了电路。而我们程序中也同样是这样。例如若此时数据库压力太大速度很慢,此时还有不断的请求访问后台,就会造成数据库崩溃。这时候hystrix容错机制,可以为客户端请求设置超时链接,添加回退的逻辑,减少集群压力。

1.1 导依赖

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>1.5.8.RELEASE</version>
  5. <relativePath/>
  6. </parent>
  7. <!-- springCloud -->
  8. <dependencyManagement>
  9. <dependencies>
  10. <dependency>
  11. <groupId>org.springframework.cloud</groupId>
  12. <artifactId>spring-cloud-dependencies</artifactId>
  13. <version>Dalston.SR3</version>
  14. <type>pom</type>
  15. <scope>import</scope>
  16. </dependency>
  17. </dependencies>
  18. </dependencyManagement>
  19.  
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-web</artifactId>
  24. </dependency>
  25. <!-- eureka客户端依赖 -->
  26. <dependency>
  27. <groupId>org.springframework.cloud</groupId>
  28. <artifactId>spring-cloud-starter-eureka</artifactId>
  29. </dependency>
  30. <!-- hystrix -->
  31. <dependency>
  32. <groupId>org.springframework.cloud</groupId>
  33. <artifactId>spring-cloud-starter-hystrix</artifactId>
  34. </dependency>

1.2 配置application.yml

  1. # 指定端口
  2. server:
  3. port: 8085
  4. context-path: /demo
  5. # 服务名称
  6. spring:
  7. application:
  8. name: hystrix
  9.  
  10. # eureka服务器地址
  11. eureka:
  12. client:
  13. serviceUrl:
  14. defaultZone: http://localhost:8761/eureka/

1.3 配置Hystrix过滤器

  1. import java.io.IOException;
  2. import javax.servlet.Filter;
  3. import javax.servlet.FilterChain;
  4. import javax.servlet.FilterConfig;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.ServletRequest;
  7. import javax.servlet.ServletResponse;
  8. import javax.servlet.annotation.WebFilter;
  9. import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
  10. /**
  11. * urlPatterns:拦截所有路径(拦截规则)
  12. * filterName:过滤器名称
  13. */
  14. @WebFilter(urlPatterns = "/*", filterName = "hystrixFilter")
  15. public class HystrixFilterConf implements Filter{
  16. public void destroy() { }
  17.  
  18. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  19. throws IOException, ServletException {
  20. // 初始化Hystrix上下文
  21. HystrixRequestContext ctx = HystrixRequestContext.initializeContext();
  22. try {
  23. chain.doFilter(request, response);
  24. } catch (Exception e) {
  25.  
  26. } finally {
  27. ctx.shutdown();
  28. }
  29. }
  30. public void init(FilterConfig arg0) throws ServletException { }
  31. }

1.4 主函数入口

  1. import org.springframework.boot.autoconfigure.SpringBootApplication;
  2. import org.springframework.boot.builder.SpringApplicationBuilder;
  3. import org.springframework.boot.web.servlet.ServletComponentScan;
  4. import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
  5. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  6. @SpringBootApplication
  7. @EnableEurekaClient //开启Eureka
  8. @EnableCircuitBreaker//开启断路器
  9. @ServletComponentScan//扫描servlet过滤器监听器
  10. public class ServerMain {
  11.  
  12. public static void main(String[] args) {
  13. new SpringApplicationBuilder(ServerMain.class).web(true).run(args);
  14. }
  15. }

二: hystrix 的 熔断,降级 机制。

2.1 回退机制案例

  1. import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
  2. import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
  3. import org.springframework.stereotype.Service;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. /**
  6. * Hystrix回退机制(熔断,降级)
  7. */
  8. @Service
  9. public class RollbackService {
  10.  
  11. /**
  12. * fallbackMethod: 指定回退方法
  13. *
  14. * coreSize: 线程池最大数量
  15. * maxQueueSize: 线程池最大队列,默认-1通过SynchronousQueue来实现; 否则使用LinkedBlockingQueue实现
  16. * queueSizeRejectionThreshold: 当maxQueueSize是LinkedBlockingQueue时,即使没有达到最大列队也会据绝请求。
  17. *
  18. * timeoutInMilliseconds: 超时时间
  19. * requestVolumeThreshold: 单位时间内超过这个多个请求失败才执行熔断
  20. */
  21. @RequestMapping(value = "/testRollback")
  22. @HystrixCommand(fallbackMethod = "myRollback",
  23. threadPoolProperties = {
  24. @HystrixProperty(name = "coreSize", value = "30"),
  25. @HystrixProperty(name = "maxQueueSize", value = "-1"),
  26. @HystrixProperty(name = "queueSizeRejectionThreshold", value = "-1")
  27. },
  28. commandProperties = {
  29. @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),
  30. @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "1")
  31. })
  32. public String testRollback() {
  33. try {// 模拟请求阻塞
  34. Thread.sleep(4000);
  35. } catch (Exception e) {
  36. }
  37. return "恭喜你访问成功!";
  38. }
  39. /** 回退方法 */
  40. public String myRollback() {
  41. return "服务器压力过大,明年再来吧!";
  42. }
  43. }

2.2 编写接口, 调用测试。

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. @RestController
  5. public class RollbackController {
  6.  
  7. @Autowired
  8. private RollbackService rollbackService;
  9.  
  10. @RequestMapping("/testRollback")
  11. public String testRollback() {
  12. return rollbackService.testRollback();
  13. }
  14. }

三: hystrix 缓存机制:hystrix的缓存有点像mybatis默认开启的一级缓存:在session关闭之前(一次会话期间),使用同样的参数调用同一个方法,实际只查询一次。

3.1 缓存逻辑

  1. import org.springframework.stereotype.Service;
  2. import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
  3. import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
  4. import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
  5. @Service
  6. public class CacheService {
  7.  
  8. @CacheResult
  9. @HystrixCommand
  10. public void cacheMember(Integer id) {
  11. System.out.println("调用 cacheMember 方法");
  12. }
  13.  
  14. /**
  15. * commandKey:缓存的key
  16. * 获取和删除必须用同一个key,并必须是同一次请求。
  17. */
  18. @CacheResult
  19. @HystrixCommand(commandKey = "myCacheKey")
  20. public void getCache(Integer id) {
  21. System.out.println("执行查询方法");
  22. }
  23. @CacheRemove(commandKey = "myCacheKey")
  24. @HystrixCommand
  25. public void removeCache(Integer id) {
  26. System.out.println("删除缓存方法");
  27. }
  28. }

3.2 缓存接口开发

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.http.MediaType;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestMethod;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. public class CacheController {
  8.  
  9. @Autowired
  10. private CacheService cacheService;
  11.  
  12. @RequestMapping(value = "/cache", method = RequestMethod.GET,
  13. produces = MediaType.APPLICATION_JSON_VALUE)
  14. public String cache() {
  15. for(int i = 0; i < 3; i++) {
  16. /** 在同一次请求里面调用了3次同一方法,会发现,控制台只
  17. * 输出了一次,说明后2次走的缓存没调方法的逻辑 */
  18. cacheService.cacheMember(1);
  19. }
  20. System.out.println("测试完毕");
  21. return "";
  22. }
  23. @RequestMapping(value = "/rc", method = RequestMethod.GET,
  24. produces = MediaType.APPLICATION_JSON_VALUE)
  25. public String testRemoveCache() {
  26. cacheService.getCache(1);
  27. cacheService.getCache(1);
  28.  
  29. cacheService.removeCache(1);
  30. System.out.println("######### 分隔线 ###########");
  31. cacheService.getCache(1);
  32. System.out.println("测试完毕");
  33. return "";
  34. }
  35. }

Hystrix (容错,回退,降级,缓存)的更多相关文章

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

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

  2. dubbo学习实践(4)之Springboot整合Dubbo及Hystrix服务熔断降级

    1. springboot整合dubbo 在provider端,添加maven引入,修改pom.xml文件 引入springboot,版本:2.3.2.RELEASE,dubbo(org.apache ...

  3. SpringCloud之Hystrix容错保护原理及配置

    1 什么是灾难性雪崩效应? 如下图的过程所示,灾难性雪崩形成原因就大致如此: 造成灾难性雪崩效应的原因,可以简单归结为下述三种: 服务提供者不可用.如:硬件故障.程序BUG.缓存击穿.并发请求量过大等 ...

  4. 转: 使用Hystrix实现自动降级与依赖隔离

    使用Hystrix实现自动降级与依赖隔离 原创 2017年06月25日 17:28:01 标签: 异步 / 降级 869 这篇文章是记录了自己的一次集成Hystrix的经验,原本写在公司内部wiki里 ...

  5. (四)Hystrix容错保护

    Feign默认是整合了Ribbon和Hystrix这两个框架,所以代码我们在上一篇的基础上进行修改,启动Eureka,service-hello,Feign 所谓的熔断机制和日常生活中见到电路保险丝是 ...

  6. SpringCloud实战-Hystrix线程隔离&请求缓存&请求合并

    接着上一篇的Hystrix进行进一步了解. 当系统用户不断增长时,每个微服务需要承受的并发压力也越来越大,在分布式环境中,通常压力来自对依赖服务的调用,因为亲戚依赖服务的资源需要通过通信来实现,这样的 ...

  7. Hystrix的回退和zuul的回退总结

    1.Hystrix的回退: Ribbon: Feign: zuul的回退:

  8. Hystrix 容错处理

    目录 雪崩效应 容错的基本思想 什么是Hystrix 简单使用 消费端使用Hystrix 注解开启 改造消费方法 @HystrixCommand 详细配置 Hystrix线程隔离策略与传播上下文 Hy ...

  9. SpringCloud断路器(Hystrix)和服务降级案列

    断路器(Hystrix) 为什么需要 Hystrix? 在微服务架构中,我们将业务拆分成一个个的服务,服务与服务之间可以相互调用(RPC).为了保证其高可用,单个服务又必须集群部署.由于网络原因或者自 ...

随机推荐

  1. mysql:联合索引及优化

    命名规则:表名_字段名1.需要加索引的字段,要在where条件中2.数据量少的字段不需要加索引3.如果where条件中是OR关系,加索引不起作用4.符合最左原则 尽量不要用or,如果可以用union代 ...

  2. C#中[JsonIgnore]意义

    字面意义是忽略序列化,就是当字段在序列化时,被[JsonIgnore]标记了的字段将被忽略序列化 序列化输出中使用Id和Name属性,但我绝对不会对AlternateName和Color感兴趣.我用[ ...

  3. 【bzoj3195】【 [Jxoi2012]奇怪的道路】另类压缩的状压dp好题

    (上不了p站我要死了) 啊啊,其实想清楚了还是挺简单的. Description 小宇从历史书上了解到一个古老的文明.这个文明在各个方面高度发达,交通方面也不例外.考古学家已经知道,这个文明在全盛时期 ...

  4. 如何理解重载与重写——Overload vs Override/Overwrite

    重载: 在同一个类中,拥有类似功能的同名方法之间的关系叫做重载. 重载的条件:1.具有相同方法名和类似功能: 2.参数的类型或者个数不同: 3.与返回值无关: 重写: 在子父类的继承关系中,子类继承父 ...

  5. Android检测WIFI连接、提示框延时消失

    Android检测系统WIFI是否连接?如没有连接,显示提示框,提示进行设置,当点击设置进入系统WIFI界面后1秒钟,提示框自动消失. 代码: ? 1 2 3 4 5 6 7 8 9 10 11 12 ...

  6. 使用struts2的内置标签,采用submit()提交表单时,浏览器报404

    如图 url是没有问题的,结果我将提交方式改为get时,发现有2个参数的name值是一样的,如下图, 解决方法:将name的值修改就OK了.

  7. Educational Codeforces Round 16 D. Two Arithmetic Progressions (不互质中国剩余定理)

    Two Arithmetic Progressions 题目链接: http://codeforces.com/contest/710/problem/D Description You are gi ...

  8. Spring Data JPA开发中遇到的问题1:org.hibernate.hql.internal.ast.QuerySyntaxException: DispatchShift is not mapped

    org.hibernate.hql.internal.ast.QuerySyntaxException: T_D_SHIFT_DISPATCH is not mapped 错误原因: 没有映射到表,经 ...

  9. url传输中+转为%2B取到变空格的问题

    一个加密串,通过url传过来后怎么也解密不了. 原串: h1tQYMmnx7jdvowi9KnaEM5dHfamJ+rbaRnvhwhUmRAvyxpA2AGzszx5k9K0qdhiQUq7m42S ...

  10. 阶段1 语言基础+高级_1-3-Java语言高级_06-File类与IO流_06 Properties集合_3_Properties集合中的方法load

    键值对文件,读取到集合中来使用 分隔符也可以用空格 读出来乱码