在项目中如何直接使用hystrix?
一、背景
最近由于一些背景原因,需要在项目中需要对接口进行限流。所以就考虑到了直接使用Hystrix。但是呢,又不想直接使用SpringCloud,而是直接引入原生,现在发现挺好用的,所以记录下来,分享出来。
二、使用方式
2.1 Jar包引入
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-javanica</artifactId>
<version>1.5.18</version>
</dependency>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.18</version>
</dependency>
引入两个包,分别是Hystrix核心包,以及直接原生的Java包
2.2 配置文件
在Resources目录下面,放上hystrix.properties文件。配置如下。
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=3000
hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests=1000
hystrix.command.default.circuitBreaker.requestVolumeThreshold=20
hystrix.command.default.metrics.rollingStats.numBuckets=10
hystrix.command.default.metrics.rollingStats.timeInMilliseconds=10000
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds=5000
hystrix.command.default.circuitBreaker.errorThresholdPercentage=50
hystrix.command.default.circuitBreaker.forceOpen=false
hystrix.command.default.circuitBreaker.forceClosed=false
hystrix.command.default.requestCache.enabled=false
hystrix.threadpool.default.coreSize=10
hystrix.threadpool.default.maximumSize=10
hystrix.threadpool.default.allowMaximumSizeToDivergeFromCoreSize=true
hystrix.threadpool.default.keepAliveTimeMinutes=1
hystrix.threadpool.default.maxQueueSize=100
hystrix.threadpool.default.queueSizeRejectionThreshold=101
hystrix.threadpool.default.metrics.rollingStats.numBuckets=10
hystrix.threadpool.default.metrics.rollingStats.timeInMilliseconds=10000
#hystrix.timer.threadpool.default.coreSize = 10
这个是一部分配置,如果需要知道更多,可以Click-Github Hystrix Wiki
2.3 设置配置
设置Hystrix的配置
/**
* <p>熔断器配置</p>
*
* @author fattycal@qq.com
* @since 2022/6/4
*/
@Configuration
public class HystrixConfig implements InitializingBean {
@Bean
public HystrixCommandAspect hystrixCommandAspect(){
// 初始化切面
return new HystrixCommandAspect();
}
@Override
public void afterPropertiesSet() throws Exception {
// 初始化熔断器配置
// 清除配置
ConfigurationManager.getConfigInstance().clear();
// 加载配置文件
ConfigurationManager.loadCascadedPropertiesFromResources("hystrix");
}
}
HystrixCommandAspect是jar包带的切面,通过切面通知,找去需要熔断的方法,然后进行处理。
@Aspect
public class HystrixCommandAspect {
//...略
@Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")
public void hystrixCommandAnnotationPointcut() {
}
@Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser)")
public void hystrixCollapserAnnotationPointcut() {
}
@Around("hystrixCommandAnnotationPointcut() || hystrixCollapserAnnotationPointcut()")
public Object methodsAnnotatedWithHystrixCommand(final ProceedingJoinPoint joinPoint) throws Throwable {
// ... 略
}
}
ConfigurationManager看看这名字,就知道是配置管理的,也不负众望,的确是用来加载配置的。
2.4 实现代码
/**
* <p>熔断器测试</p>
*
* @author fattycal@qq.com
* @since 2022/6/4
*/
@RestController
public class HystrixTestController {
@GetMapping("/hystrix")
@HystrixCommand(commandKey = "hystrixTestController-getHello", threadPoolKey = "hystrixTestController-getHello",
fallbackMethod = "getHelloFallback")
public String getHello(){
try {
// 执行太快不便于测试
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "TEST Hystrix";
}
public String getHelloFallback(Throwable error){
// 打印日志
System.out.println("TEST Hystrix: " + error.getMessage());
return "TEST Hystrix: " + error.getMessage();
}
}
代码没有啥花里胡哨的,直接在需要熔断的方法上面加上HystrixCommond。
commandKey和threadPoolKey是自己设置的,可以为这个方法定制线程数、核心线程等配置(在hystrix.properties中添加)。给出示例如下。
#-------------------------------------------------------------------
hystrix.threadpool.hystrixTestController-getHello.coreSize=1
hystrix.threadpool.hystrixTestController-getHello.maximumSize=2
hystrix.threadpool.hystrixTestController-getHello.maxQueueSize=1
hystrix.threadpool.hystrixTestController-getHello.queueSizeRejectionThreshold=2
#-------------------------------------------------------------------
至此,完成了所有的配置和准备,接下来直接测试
三、测试试验
直接从Jmeter官网下载jmeter,拿到跑测试, 具体下载过程就不一样展示了,直接贴出测试结果。
![测试结果]](https://img2022.cnblogs.com/blog/1495071/202206/1495071-20220604154925529-898198001.jpg)
由于为这个方法设置的核心线程数、线程数、队列数都不大,很容易测试出结果。我们可以从console中很明显的看到熔断器打开,说明方法被执行到。
在从Jmeter中查看一下结果,也是可以佐证我们的效果。测试图如下:

四、总结
自此,整个流程是走完了,可以看到效果着实起来了。 Hystrix知识限流熔断中的一种方案,大家可以结合实际情况做出更多的选择。
如果有问题,欢迎指出,谢谢!
在项目中如何直接使用hystrix?的更多相关文章
- Hystrix在项目中实践
Hystrix在项目中实践 https://mp.weixin.qq.com/s/4Fg0COnWRB3rRWfxbJt7gA
- 在dropwizard中使用feign,使用hystrix
前言 用惯了spring全家桶之后,试试dropwizard的Hello World也别有一帆风味.为了增强对外访问API的能力,需要引入open feign.这里简单在dropwizard中使用fe ...
- springboot项目中使用maven resources
maven resource 组件可以把pom的变量替换到相关的resouces目录中的资源文件变量 示例项目:内容中心 (文章管理) 生成jar包,生成docker ,生成k8s文件 1.项目结构 ...
- 网关中加入熔断机制(Hystrix)
网关中加入熔断机制 在网关中加入熔断机制 添加依赖项 spring-cloud-gateway项目POM文件加入spring-cloud-starter-netflix-hystrix <dep ...
- VS项目中使用Nuget还原包后编译生产还一直报错?
Nuget官网下载Nuget项目包的命令地址:https://www.nuget.org/packages 今天就遇到一个比较奇葩的问题,折腾了很久终于搞定了: 问题是这样的:我的解决方案原本是好好的 ...
- ABP项目中使用Swagger生成动态WebAPI
本文是根据角落的白板报的<使用ABP实现SwaggerUI,生成动态webapi>一文的学习总结,感谢原文作者角落的白板报. 1 安装Swashbuckle.core 1.1 选择WebA ...
- iOS 之项目中遇到的问题总结
昨天去一家公司面试,面试官问了我在项目开发中遇到过哪些问题,是什么引起的,怎样解决的? 当时由于有点小紧张只说出了一两点,现在就来好好总结一下. 问题: 1.两表联动 所谓的两表联动就是有左右两个表格 ...
- My97DatePicker时间控件在项目中的应用
一.下载My97DatePicker的压缩包My97DatePicker.rar,解压. 注:My97DatePicker最新版本有开发包,项目中使用时删掉,以便节省空间,提高程序的运行效率. 二.在 ...
- 在项目中同时使用Objective-C和Swift
苹果发布的Swift语言可以和之前的Objective-C语言同时存在于一个项目中. 可能有人会认为是同一个类文件中既可以有Objective-C也可以有Swift,这是不对的.同一个类文件或同一个代 ...
随机推荐
- MySQL中 tinyint、bigint、bit、text、decimal、year、date、time、datetime、timestamp等对应Java中什么类型
MySQL中字段名称对应的Java类型 MySQL字段名 Java数据类型 varchar String text String bigint Long(已经有长度了,在mysql建表中的length ...
- java基础-多线程-线程组
线程组 * Java中使用ThreadGroup来表示线程组,它可以对一批线程进行分类管理,Java允许程序直接对线程组进行控制. * 默认情况下,所有的线程都属于主线程组. * public fi ...
- 用 rollup + gulp 造个轮子,别说还挺香
前戏 我是16年入了前端的坑,17年知道了gulp和rollup这两个玩意儿.由于那时webpack势头很猛,便一直没有正眼瞧过它一眼. 直到20年进了一家小公司,做了很多类似的小项目,相同的代码拷来 ...
- title与h1的区别、b与strong的区别、i与em的区别
strong标签有语义,是起到加重语气的效果,而b标签是没有的,b标签只是一个简单加粗标签.b标签之间的字符都设为粗体,strong标签加强字符的语气都是通过粗体来实现的,而搜索引擎更侧重strong ...
- WIN DLL劫持提权
WIN DLL劫持提权 原理: Windows程序启动的时候需要DLL.如果这些DLL 不存在,则可以通过在应用程序要查找的位置放置恶意DLL来提权.通常,Windows应用程序有其预定义好的搜索DL ...
- springboot+mybatis实现数据分页(三种方式)
项目准备 1.创建用户表 2.使用spring初始化向导快速创建项目,勾选mybatis,web,jdbc,driver 添加lombok插件 <?xml version="1.0&q ...
- Linux磁盘分区fdisk命令操作(简洁版)
实例(环境为: CentOS Linux release 7.2.1511 (Core), 3.10.0-327.el7.x86_64) 选择要具体操作的第二块磁盘(linux下一切是文件形式对应): ...
- Sql获取表所有列名字段——select * 替换写法,Sqlserver、Oracle、PostgreSQL、Mysql
实际开发中经常用到select * from table,往往需要知道具体的字段,这个时候再去数据库中翻或者查看数据字典比较麻烦.为了方便,自己特意写了一个小函数f_selectall,针对SqlSe ...
- 深入理解Kafka核心设计及原理(四):主题管理
转载请注明出处:https://www.cnblogs.com/zjdxr-up/p/16124354.html 目录: 4.1创建主题 4.2 优先副本的选举 4.3 分区重分配 4.4 如何选择合 ...
- defer综合
A "defer" statement invokes a function whose execution is deferred to the moment the surro ...