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

1.1 导依赖

    <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/>
</parent>
<!-- springCloud -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- eureka客户端依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<!-- hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

1.2 配置application.yml

# 指定端口
server:
port: 8085
context-path: /demo
# 服务名称
spring:
application:
name: hystrix # eureka服务器地址
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/

1.3 配置Hystrix过滤器

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
/**
* urlPatterns:拦截所有路径(拦截规则)
* filterName:过滤器名称
*/
@WebFilter(urlPatterns = "/*", filterName = "hystrixFilter")
public class HystrixFilterConf implements Filter{
public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// 初始化Hystrix上下文
HystrixRequestContext ctx = HystrixRequestContext.initializeContext();
try {
chain.doFilter(request, response);
} catch (Exception e) { } finally {
ctx.shutdown();
}
}
public void init(FilterConfig arg0) throws ServletException { }
}

1.4 主函数入口

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient //开启Eureka
@EnableCircuitBreaker//开启断路器
@ServletComponentScan//扫描servlet过滤器监听器
public class ServerMain { public static void main(String[] args) {
new SpringApplicationBuilder(ServerMain.class).web(true).run(args);
}
}

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

2.1 回退机制案例

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Hystrix回退机制(熔断,降级)
*/
@Service
public class RollbackService { /**
* fallbackMethod: 指定回退方法
*
* coreSize: 线程池最大数量
* maxQueueSize: 线程池最大队列,默认-1通过SynchronousQueue来实现; 否则使用LinkedBlockingQueue实现
* queueSizeRejectionThreshold: 当maxQueueSize是LinkedBlockingQueue时,即使没有达到最大列队也会据绝请求。
*
* timeoutInMilliseconds: 超时时间
* requestVolumeThreshold: 单位时间内超过这个多个请求失败才执行熔断
*/
@RequestMapping(value = "/testRollback")
@HystrixCommand(fallbackMethod = "myRollback",
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "30"),
@HystrixProperty(name = "maxQueueSize", value = "-1"),
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "-1")
},
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "1")
})
public String testRollback() {
try {// 模拟请求阻塞
Thread.sleep(4000);
} catch (Exception e) {
}
return "恭喜你访问成功!";
}
/** 回退方法 */
public String myRollback() {
return "服务器压力过大,明年再来吧!";
}
}

2.2 编写接口, 调用测试。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RollbackController { @Autowired
private RollbackService rollbackService; @RequestMapping("/testRollback")
public String testRollback() {
return rollbackService.testRollback();
}
}

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

3.1 缓存逻辑

import org.springframework.stereotype.Service;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
@Service
public class CacheService { @CacheResult
@HystrixCommand
public void cacheMember(Integer id) {
System.out.println("调用 cacheMember 方法");
} /**
* commandKey:缓存的key
* 获取和删除必须用同一个key,并必须是同一次请求。
*/
@CacheResult
@HystrixCommand(commandKey = "myCacheKey")
public void getCache(Integer id) {
System.out.println("执行查询方法");
}
@CacheRemove(commandKey = "myCacheKey")
@HystrixCommand
public void removeCache(Integer id) {
System.out.println("删除缓存方法");
}
}

3.2 缓存接口开发

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CacheController { @Autowired
private CacheService cacheService; @RequestMapping(value = "/cache", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public String cache() {
for(int i = 0; i < 3; i++) {
/** 在同一次请求里面调用了3次同一方法,会发现,控制台只
* 输出了一次,说明后2次走的缓存没调方法的逻辑 */
cacheService.cacheMember(1);
}
System.out.println("测试完毕");
return "";
}
@RequestMapping(value = "/rc", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public String testRemoveCache() {
cacheService.getCache(1);
cacheService.getCache(1); cacheService.removeCache(1);
System.out.println("######### 分隔线 ###########");
cacheService.getCache(1);
System.out.println("测试完毕");
return "";
}
}

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. A1011

    找最大的,然后按规定计算后输出. 没啥可说的,除非犯了愚蠢的错误(比如把j写成i这种),按题目要求写就是了. #include<cstdio> int main(){ ]={'W','T' ...

  2. vue-cli3热更新配置,解决热更新失败的问题,保存代码浏览器自动刷新

    在vue,config.js中配置css热更新 const IS_PROD = ['production', 'test'].includes(process.env.NODE_ENV) css: { ...

  3. css盒子模型中的border属性

        认识border属性 我们可以通过boder属性来为元素设置边框:元素的边框 (border) 是围绕元素内容和内边距的一条或多条线.CSS border 属性允许你规定元素边框的样式.宽度和 ...

  4. VGA驱动时序说明

    根据不同的显示器分辨率,需要不同的刷新频率. 其中显示模式中@60表示显示器1秒钟刷新60帧. 其中时钟(MHz),表示FPGA输出给显示器的时钟频率.需要我们配置PLL的时钟频率为对应频率. 其中行 ...

  5. Socket通信前必须考虑的几件事

    如何处理I/O?是让程序阻塞等待响应,还是在后台处理这些事?这是软件设计的关键因素.阻塞式的I/O操作会让程序架构难以扩展,而后台处理I/O也是比较困难的.   如何处理那些临时的.来去自由的组件?我 ...

  6. [luogu]P2279 [HNOI2003]消防局的设立[贪心]

    [luogu]P2279 [HNOI2003]消防局的设立 题目描述 2020年,人类在火星上建立了一个庞大的基地群,总共有n个基地.起初为了节约材料,人类只修建了n-1条道路来连接这些基地,并且每两 ...

  7. MongoDB可视化工具的安装

    MongoDBCompass MongoDB Compass是一款优秀可靠的mongodb可视化数据库管理软件.可以更加方便地与mongodb数据库进行交互,支持对数据库进行查询.分析或者查看数据库的 ...

  8. ORACLE 临时表空间管理

     临时表空间和临时段 临时表空间用于存放排序.临时表等数据,其信息不需要REDO,因此临时表的DML操作往往比普通表产生的REDO少很多.临时表数据变化不产生REDO,UNDO数据变化产生REDO.临 ...

  9. JXLS (Excel导入、导出工具使用)

    JXLS (Excel导入.导出工具使用) 1:简介: jxls是一个简单的.轻量级的excel导出库,使用特定的标记在excel模板文件中来定义输出格式和布局.java中成熟的excel导出工具有p ...

  10. WinForm实现最小化右下角

    首先,要在窗体里面加入这么两个控件,左边的是托盘控件,右边的是菜单控件. 然后设置窗体的FormClosing事件: if (e.CloseReason == CloseReason.UserClos ...