通过hystrix可以进行服务的限流、熔断、降级

配置

服务端Eureka

server:
port: 8761 # 指定该Eureka实例的端口
eureka:
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://localhost:8761/eureka/
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}

pom

<!-- 引入spring boot的依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies> <!-- 引入spring cloud的依赖 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

服务提供者

server:
port: 8002
spring:
application:
name: microservice-provider-user
jpa:
generate-ddl: false
show-sql: true
hibernate:
ddl-auto: none
datasource: # 指定数据源
platform: h2 # 指定数据源类型
schema: classpath:schema.sql # 指定h2数据库的建表脚本
data: classpath:data.sql # 指定h2数据库的数据脚本
logging: # 配置日志级别,让hibernate打印出执行的SQL
level:
root: INFO
org.hibernate: INFO
org.hibernate.type.descriptor.sql.BasicBinder: TRACE
org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
@EnableDiscoveryClient
@SpringBootApplication
public class ProviderUserApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderUserApplication.class, args);
}
}
@GetMapping("/{id}")
public User findById(@PathVariable Long id) throws Exception {
logger.info("用户中心接口:查询用户"+ id +"信息");
//测试超时触发降级
/*int sleepTime = new Random().nextInt(2000);
logger.info("sleepTime:" + sleepTime);
Thread.sleep(sleepTime);*/ //测试熔断,传入不存在的用户id模拟异常情况
if (id == 10) {
throw new NullPointerException();
} //测试限流,线程资源隔离,模拟系统执行速度很慢的情况
// Thread.sleep(3000); User findOne = userRepository.findOne(id);
return findOne;
}

客户端

server:
port: 8010
spring:
application:
name: microservice-consumer-order
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 20000
circuitBreaker:
requestVolumeThreshold: 3
sleepWindowInMilliseconds: 10000
@EnableDiscoveryClient
@SpringBootApplication
@EnableCircuitBreaker
public class ConsumerOrderApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
} public static void main(String[] args) {
SpringApplication.run(ConsumerOrderApplication.class, args);
}
}
@HystrixCommand(fallbackMethod = "findByIdFallback",
groupKey = "orderUserGroup",
threadPoolKey = "orderUserIdThreadPool",
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "2"),
@HystrixProperty(name = "maxQueueSize", value = "2"),
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "1") })
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
logger.info("================请求用户中心接口,用户id:" + id + "==============");
return restTemplate.getForObject("http://microservice-provider-user/" + id, User.class);
} public User findByIdFallback(Long id) {
User user = new User();
user.setId(-1L);
user.setName("默认用户");
return user;
}

部分注解意思如下:

  • CommandGroupKey:配置全局唯一标识服务分组的名称,比如,库存系统就是一个服务分

    组。当我们监控时,相同分组的服务会聚合在一起,必填选项。
  • CommandKey:配置全局唯一标识服务的名称,比如,库存系统有一个获取库存服务,那么

    就可以为这个服务起一个名字来唯一识别该服务,如果不配置,则默认是简单类名。
  • ThreadPoolKey:配置全局唯一标识线程池的名称,相同线程池名称的线程池是同一个,如

    果不配置,则默认是分组名,此名字也是线程池中线程名字的前缀。
  • ThreadPoolProperties:配置线程池参数,coreSize配置核心线程池大小和线程池最大大

    小,keepAliveTimeMinutes是线程池中空闲线程生存时间(如果不进行动态配置,那么是没

    有任何作用的),maxQueueSize配置线程池队列最大大小,
  • queueSizeRejectionThreshold限定当前队列大小,即实际队列大小由这个参数决定,通过

    改变queueSizeRejectionThreshold可以实现动态队列大小调整。
  • CommandProperties:配置该命令的一些参数,如executionIsolationStrategy配置执行隔

    离策略,默认是使用线程隔离,此处我们配置为THREAD,即线程池隔离。

Hystrix相关配置:

  • hystrix.command.default和hystrix.threadpool.default中的default为默认CommandKey

    Command Properties
Execution相关的属性的配置:
  • hystrix.command.default.execution.isolation.strategy 隔离策略,默认是Thread, 可选Thread|

    Semaphore
  • hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds 命令执行超时时间,默认1000ms
  • hystrix.command.default.execution.timeout.enabled 执行是否启用超时,默认启用true
  • hystrix.command.default.execution.isolation.thread.interruptOnTimeout 发生超时是是否中断,默认true
  • hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests 最大并发请求数,默认10,该参数当使用ExecutionIsolationStrategy.SEMAPHORE策略时才有效。如果达到最大并发请求数,请求会被拒绝。理论上选择semaphore size的原则和选择thread size一致,但选用semaphore时每次执行的单元要比较小且执行速度快(ms级别),否则的话应该用thread。semaphore应该占整个容器(tomcat)的线程池的一小部分。Fallback相关的属性

    这些参数可以应用于Hystrix的THREAD和SEMAPHORE策略
  • hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests 如果并发数达到该设置值,请求会被拒绝和抛出异常并且fallback不会被调用。默认10
  • hystrix.command.default.fallback.enabled 当执行失败或者请求被拒绝,是否会尝试调用hystrixCommand.getFallback() 。默认true

    Circuit Breaker相关的属性
  • hystrix.command.default.circuitBreaker.enabled 用来跟踪circuit的健康性,如果未达标则让request短路。默认true
  • hystrix.command.default.circuitBreaker.requestVolumeThreshold 一个rolling window内最小的请求数。如果设为20,那么当一个rolling window的时间内(比如说1个rolling window是10秒)收到19个请求,即使19个请求都失败,也不会触发circuit break。默认20
  • hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds 触发短路的时间值,当该值设为5000时,则当触发circuit break后的5000毫秒内都会拒绝request,也就是5000毫秒后才会关闭circuit。默认5000
  • hystrix.command.default.circuitBreaker.errorThresholdPercentage错误比率阀值,如果错误率>=该值,circuit会被打开,并短路所有请求触发fallback。默认50
  • hystrix.command.default.circuitBreaker.forceOpen 强制打开熔断器,如果打开这个开关,那么拒绝所有request,默认false
  • hystrix.command.default.circuitBreaker.forceClosed 强制关闭熔断器 如果这个开关打开,circuit将一直关闭且忽略circuitBreaker.errorThresholdPercentage Metrics相关参数
  • hystrix.command.default.metrics.rollingStats.timeInMilliseconds 设置统计的时间窗口值的,毫秒值,circuit break 的打开会根据1个rolling window的统计来计算。若rolling window被设为10000毫秒,则rolling window会被分成n个buckets,每个bucket包含success,failure,timeout,rejection的次数

    的统计信息。默认10000
  • hystrix.command.default.metrics.rollingStats.numBuckets 设置一个rolling window被划分的数量,若numBuckets=10,rolling window=10000,那么一个bucket的时间即1秒。必须符合rolling window% numberBuckets == 0。默认10
  • hystrix.command.default.metrics.rollingPercentile.enabled 执行时是否enable指标的计算和跟踪,默认true
  • hystrix.command.default.metrics.rollingPercentile.timeInMilliseconds 设置rolling

    percentile window的时间,默认60000
  • hystrix.command.default.metrics.rollingPercentile.numBuckets 设置rolling percentile window的numberBuckets。逻辑同上。默认6
  • hystrix.command.default.metrics.rollingPercentile.bucketSize 如果bucket size=100,window=10s,若这10s里有500次执行,只有最后100次执行会被统计到bucket里去。增加该值会增加内存开销以及排序的开销。默认100
  • hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds 记录health 快照(用来统计成功和错误绿)的间隔,默认500ms Request Context 相关参数
  • hystrix.command.default.requestCache.enabled 默认true,需要重载getCacheKey(),返回null时不缓存
  • hystrix.command.default.requestLog.enabled 记录日志到HystrixRequestLog,默认true

    Collapser Properties 相关参数
  • hystrix.collapser.default.maxRequestsInBatch 单次批处理的最大请求数,达到该数量触发批处理,默认Integer.MAX_VALUE
  • hystrix.collapser.default.timerDelayInMilliseconds 触发批处理的延迟,也可以为创建批处理的时间+该值,默认10
  • hystrix.collapser.default.requestCache.enabled 是否对HystrixCollapser.execute() and HystrixCollapser.queue()的cache,默认true ThreadPool 相关参数 线程数默认值10适用于大部分情况(有时可以设置得更小),如果需要设置得更大,那有个基本得公式可以

    follow:

    requests per second at peak when healthy × 99th percentile latency in seconds + some

    breathing room

    每秒最大支撑的请求数 (99%平均响应时间 + 缓存值)

    比如:每秒能处理1000个请求,99%的请求响应时间是60ms,那么公式是:

    1000 (0.060+0.012)

    基本得原则时保持线程池尽可能小,他主要是为了释放压力,防止资源被阻塞。

    当一切都是正常的时候,线程池一般仅会有1到2个线程激活来提供服务
  • hystrix.threadpool.default.coreSize 并发执行的最大线程数,默认10
  • hystrix.threadpool.default.maxQueueSize BlockingQueue的最大队列数,当设为-1,会使用
  • SynchronousQueue,值为正时使用LinkedBlcokingQueue。该设置只会在初始化时有效,之后不能修改
  • threadpool的queue size,除非reinitialising thread executor。默认-1。
  • hystrix.threadpool.default.queueSizeRejectionThreshold 即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,请求也会被拒绝。因为maxQueueSize不能被动态修改,这个参数将允许我们动态设置该值。if maxQueueSize == ­1,该字段将不起作用
  • hystrix.threadpool.default.keepAliveTimeMinutes 如果corePoolSize和maxPoolSize设成一样(默认实现)该设置无效。如果通过plugin(https://github.com/Netflix/Hystrix/wiki/Plugins)使用自定义实现,该设置才有用,默认1.
  • hystrix.threadpool.default.metrics.rollingStats.timeInMilliseconds 线程池统计指标的时间,默认10000
  • hystrix.threadpool.default.metrics.rollingStats.numBuckets 将rolling window划分为n个buckets,默认10

代码链接:https://pan.baidu.com/s/11dGxsOqUR_Q_0cTZ_mnGKw

提取码:fnky

hystrix降级初步学习的更多相关文章

  1. json2.js的初步学习与了解

    json2.js的初步学习与了解,想要学习json的朋友可以参考下. json2.js的初步学习与了解 1.)该js的下载地址是:http://www.json.org/json2.js 2.)在页面 ...

  2. 老周的ABP框架系列教程 -》 一、框架理论初步学习

    老周的ABP框架系列教程 -- 一.框架理论初步学习   1. ABP框架的来源与作用简介 1.1  简介 1.1.1       ABP框架全称为"ASP.NET Boilerplate ...

  3. 初步学习nodejs,业余用node写个一个自动创建目录和文件的小脚本,希望对需要的人有所帮助

    初步学习nodejs,业余用node写个一个自动创建目录和文件的小脚本,希望对需要的人有所帮助,如果有bug或者更好的优化方案,也请批评与指正,谢谢,代码如下: var fs = require('f ...

  4. EF Codefirst 初步学习(二)—— 程序管理命令 更新数据库

    前提:搭建成功codefirst相关代码,参见EF Codefirst  初步学习(一)--设置codefirst开发模式 具体需要注意点如下: 1.确保实体类库程序生成成功 2.确保实体表类库不缺少 ...

  5. 初步学习python

    自计算机诞生以来,也伴随着计算机语言的诞生,现在,全世界的编程语言有600多种,但流行的编程语言也就20多种. Java和C一直占据着前两名.但是近年来伴随着人工智能的发展,Python发展迅猛,以其 ...

  6. Git的初步学习

    前言 感谢! 承蒙关照~ Git的初步学习 为什么要用Git和Github呢?它们的出现是为了用于提交项目和存储项目的,是一种很方便的项目管理软件和网址地址. 接下来看看,一家公司的基本流程图: 集中 ...

  7. 语法分析器初步学习——LISP语法分析

    语法分析器初步学习——LISP语法分析 本文参考自vczh的<如何手写语法分析器>. LISP的表达式是按照前缀的形式写的,比如(1+2)*(3+4)在LISP中会写成(*(+ 1 2)( ...

  8. 状态保持以及AJAX的初步学习

    嘿嘿,今天学习的有点迷茫哦,主要学习把验证码使用在登录页面时间的一些逻辑,学习这个时间并没有那么的迷惑哦,可是自己写程序时间倒是有点反应迟钝,不过还好总是在最后搞清楚啦,另外就是一步一步的学习是接近项 ...

  9. LinQ的初步学习与总结

    嘿嘿,说起来ORM和LinQ,就感觉离我好遥远的,在学校是没有学习的,所以总感觉学习了LinQ就是大神,现在嘛,终于也体会一点,感觉LinQ只是初步学习,没有太难,当然以后使用在项目中就没有这样的简单 ...

随机推荐

  1. 一个free异常引发的异常

    有同事反馈说自己的线程不工作,查看堆栈发现其打印如下: # # # # # # # # , info= # <signal handler called> # # # # # # # , ...

  2. jQuery的appendTo案例

    案例要求:点击双击第一个下拉列表框的选项可以把对应选项移到第二个下拉列表框中,选中第一个列表框的选项(可多选)单击-->按钮可使被选中项移动到右边下拉列表框中,单击==>按钮时将左边的所有 ...

  3. cdn贝四层协议配置端口映射TCP端口转发

    端口映射就是将外网主机的IP地址的一个端口映射到内网中一台机器,提供相应的服务.当用户访问该IP的这个端口时,服务器自动将请求映射到对应局域网内部的机器上.端口映射有动态和静态之分 1.安装好节点后初 ...

  4. adc指令

    adc是带进位加法指令,它利用了CF位上记录的进位值. 指令格式: adc 操作对象1,操作对象2 功能:操作对象1 = 操作对象1 + 操作对象2 + CF 例如指令 adc  ax,bx实现的功能 ...

  5. pip 国内源 配置

    pip 国内源 配置 2017年12月09日 16:05:20 阅读数:183 最近使用 pip 安装包,动辄十几 k 甚至几 k 的下载速度,确实让人安装的时候心情十分不好.所以还是要给 pip 换 ...

  6. Sonar+maven+jenkins集成,Java代码走查

    Sonar服务在Sonar安装与使用篇已经介绍过,此文章不再说了 Jenkins的安装与配置方法参考http://www.cnblogs.com/chenchen-tester/p/6408815.h ...

  7. golang环境 centos 7

    https://blog.csdn.net/ggq89/article/details/82682171  Linux下Go的安装.配置 .升级和卸载 https://blog.csdn.net/we ...

  8. 受欢迎的牛[HAOI2006]

    --BZOJ1051 Description 每一头牛的愿望就是变成一头最受欢迎的牛.现在有N头牛,给你M对整数(A,B),表示牛A认为牛B受欢迎. 这 ​ 种关系是具有传递性的,如果A认为B受欢迎, ...

  9. c++沉思录 学习笔记 第六章 句柄(引用计数指针雏形?)

    一个简单的point坐标类 class Point {public: Point():xval(0),yval(0){} Point(int x,int y):xval(x),yval(y){} in ...

  10. exception is java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make su re that file is correct.

    spring cloud 项目使用maven 打包报错“No auto configuration classes found in META-INF/spring.factories” 在pom.x ...