spring cloud Hystrix
spring cloud Hystrix
文章目录
- spring cloud Hystrix
- pom.xml依赖
- 开启短路器功能
- 服务降级
- @HystrixCommand的fallbackMethod
- 配置默认的服务降级方法
- 使用openfeign中的hystrix
- 配置application.yml
- @FeignClient的fallback属性配置服务降级的类
- 服务熔断
- @HystrixCommand配置断路器
- 使用案例
- Hystrix的仪表盘
- pom.xml依赖
- 启动类
- 访问接口
- 监控展示
- 报错Unable to connect to Command Metric Stream.
pom.xml依赖
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId><version>2.2.2.RELEASE</version>
</dependency>
开启短路器功能
要使用Hystrix服务这些功能的,需要在主启动类添加@EnableCircuitBreaker注解
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentApplication8003 {public static void main(String[] args) {SpringApplication.run(PaymentApplication8003.class,args);}}
服务降级
服务降级,当服务器压力剧增的情况下,根据当前业务情况及流量对一些服务和页面有策略的降级,以此释放服务器资源以保证核心任务的正常运行。
处理超时,处理异常等都会触发服务降级,当某个微服务发生一些网络拥挤现象时,微服务模块未能及时返回数据时,我们就可以通过服务降级对超时等现象进行处理(如返回一些提示信息,通知用户系统繁忙稍后在试),这样就可以及时释放掉资源,以免发生过长的等待,导致资源的长时间占用。
@HystrixCommand的fallbackMethod
@HystrixCommand中的fallbackMethod指定服务降级方法
配置服务降级@HystrixCommand中的fallbackMethod属性进行配置,commandProperties属性用于设置command的配置属性。
@HystrixCommand(fallbackMethod = "createFallback",commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")})
public int create(Payment payment) {return paymentDao.create(payment);
}public int createFallback(Payment payment){System.out.println("创建出错");return Integer.MAX_VALUE;
}
配置默认的服务降级方法
通过@DefaultProperties可以配置一些默认的配置,如:defaultFallback,commandProperties等。
下面的代码中的PaymentServiceImpl配置了一个defaultFallback,当一个方法上面的@HystrixCommand
没有配置相应的属性时,默认使用@DefaultProperties
声明的属性。所以下面的代码中create方法使用的降级方法是createFallback
,而getPaymentById
则使用默认的global_fallbackfunction
注意点:服务降级的方法应该跟源配置方法一致,如:int create(Payment payment)那么它的服务降级方法返回值必须为int,传入参数必须为Payment类型。
@Service
@DefaultProperties(defaultFallback = "global_fallbackfunction")
public class PaymentServiceImpl implements PaymentService {@Resourceprivate PaymentDao paymentDao;@HystrixCommand(fallbackMethod = "createFallback",commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")})public int create(Payment payment) {return paymentDao.create(payment);}@HystrixCommandpublic Payment getPaymentById(int id) {return paymentDao.getPaymentById(id);}//---------------------------------------------------------------public int createFallback(Payment payment){System.out.println("创建出错");return Integer.MAX_VALUE;}public Payment global_fallbackfunction(int id){System.out.println("全局默认fallback方法");return null;}
}
使用openfeign中的hystrix
openfeign中带有hystrix,使用openfeign也可以配置服务降级功能。
配置application.yml
通过feign.hystrix.enabled开启hystrix的功能,默认是关闭的。
feign:hystrix:enabled: true
@FeignClient的fallback属性配置服务降级的类
用过openfeign的应该都知道使用@FeignClient注解,用于定义要代理的服务端的接口,打上这个注解后,feign就会扫描这个注解生成代理类,然后通过这个代理类就能直接调用服务端的暴露的接口了。
1.服务端暴露的接口
这个服务端已经将服务注册到Eureka上,并且这个服务名称为CLOUD-PAYMENT-SERVICE
。
@RestController
@Slf4j
public class PaymentController {@Resourceprivate PaymentServiceImpl paymentServiceImpl;@Value("${server.port}")private String port;@GetMapping("/payment/get/{id}")public ResponseMessage getPaymentById(@PathVariable("id") int id){Payment payment = paymentServiceImpl.getPaymentById(id);return ResultFactory.buidResult(200,"成功"+port,payment);}
}
2.消费端指定Feign要代理的接口
这里是消费端的代码,通过@FeignClient指定要代理服务名称,要代理的接口。然后openFeign将会生成代理对象。
//代理CLOUD-PAYMENT-SERVICE服务的接口,并指定服务降级的类
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE",fallback = PaymentFallback.class)
public interface PaymentOpenfeginService {//服务端的接口@GetMapping("/payment/get/{id}")public ResponseMessage getPaymentById(@PathVariable("id") int id);
}
3.使用代理对象
@RestController
@Slf4j
public class OrderController {//注入接口的代理对象@Resourceprivate PaymentOpenfeginService paymentOpenfeginService;@GetMapping("/comsumer/payment/get/{id}")public ResponseMessage getPaymentById(@PathVariable("id") int id){//直接通过代理对象即可调用服务端接口return paymentOpenfeginService.getPaymentById(id);}}
4.编写服务降级类
上面@FeignClient
注解通过属性fallback指定了要降级的类,当openFeign的代理类的代理方法需要进行服务降级时,就会通过fallback中指定的类中对应的方法进行服务降级方法的调用。
@Component
public class PaymentFallback implements PaymentOpenfeginService {//当getPaymentById需要服务降级时,将调用其对应我服务降级方法public ResponseMessage getPaymentById(int id) {System.out.println("服务降级");return null;}
}
服务熔断
服务熔断,一种源于电子工程的断路器的概念。
微服务往往过个服务中间进行调用,而多个服务之间进行调用就会形成一个调用链。当下游服务因访问压力过大而响应变慢或失败,上游服务为了保护系统整体的可用性,可以暂时切断对下游服务的调用。
说穿了就是当某个微服务发生网络拥挤现象,而触发多次服务降级措施时,我们就可以对改服务的调用进行切断(服务恢复前调用不再调用),这就像电路的断路器一样,咔的一下断闸。等到发生故障的微服务能再次被调用的时候,再恢复调用。
@HystrixCommand配置断路器
服务熔断还是需要使用到@HystrixCommand注解。
关于@HystrixProperty的属性去哪找,我们可以通过HystrixPropertiesManager
这个类去获取属性,这个类就是用于获取配置属性的。
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
HystrixCommandProperties的默认值可以从这个类找到
import org.springframework.cloud.netflix.hystrix.HystrixProperties;
使用案例
下面的代码配置了一个断路器,有一些特点:
- 他的降级方法是
fallbackfunction
- 超时时间窗口为10秒
- 统计近10请求,失败率超过60%及打开断路器
还有一点要注意的是,断路器是可以自动关闭的,如果断路器为开启状态(服务熔断了),当有一些请求到达这里时,断路器尝试开启,就是半开,如果服务恢复,
@GetMapping("/payment/get/{id}")@HystrixCommand(fallbackMethod = "fallbackfunction",commandProperties = {@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED,value = "true"),//开启断路器@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,value = "10"),//请求次数@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS,value = "10000"),//时间窗口@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE,value = "60")})//失败率阈值
public ResponseMessage getPaymentById(@PathVariable("id") int id){Payment payment = paymentServiceImpl.getPaymentById(id);return ResultFactory.buidResult(200,"成功"+port,payment);
}public ResponseMessage fallbackfunction(){return ResultFactory.buildFailResult("失败");
}
Hystrix的仪表盘
pom.xml依赖
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix-dashboard --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
启动类
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardRun {public static void main(String[] args) {SpringApplication.run(HystrixDashboardRun.class,args);}
}
访问接口
访问接口跟你配置的服务端口有关,我这里配置的是9981
http://localhost:9981/hystrix
然后输入你要监控的服务端口即可使用,注意被监控的服务必须配置好了spring-boot-starter-actuator,要不就无法进行监控。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
监控展示
报错Unable to connect to Command Metric Stream.
请在被监控测配置一个bean,以解决无法获得监控流服务。
@Bean
public ServletRegistrationBean getServlet() {HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);registrationBean.setLoadOnStartup(1);registrationBean.addUrlMappings("/hystrix.stream");registrationBean.setName("HystrixMetricsStreamServlet");return registrationBean;}
spring cloud Hystrix相关推荐
- Spring Cloud Hystrix理解与实践(一):搭建简单监控集群
前言 在分布式架构中,所谓的断路器模式是指当某个服务发生故障之后,通过断路器的故障监控,向调用方返回一个错误响应,这样就不会使得线程因调用故障服务被长时间占用不释放,避免故障的继续蔓延.Spring ...
- Spring Cloud 学习笔记(四)-Spring Cloud Hystrix
Spring Cloud 学习笔记(四)-Spring Cloud Hystrix 由于前一阵子项目的原因,今天才继续弄上,今天想学习一下Hystrix组件 这个组件还挺抽象的,最开始我一直没太明白, ...
- Spring Cloud Hystrix 服务容错保护
在微服务架构中,我们将系统拆分成了很多服务单元,各单元的应用间通过服务注册与订阅的方式互相依赖.由于每个单元都在不同的进程中运行,依赖通过远程调用的方式执行,这样就有可能因为网络原因或是依赖服务自身间 ...
- Spring Cloud Hystrix 源码系列:工作原理
Hystrix 译为 "豪猪",豪猪的棘刺能保护自己不受天敌伤害,代表了强大的防御能力.Hystrix 基于 RxJava 进行实现,RxJava 是一种基于观察者模式的响应式编程 ...
- Spring Cloud Hystrix的请求合并
通常微服务架构中的依赖通过远程调用实现,而远程调用中最常见的问题就是通信消耗与连接数占用.在高并发的情况之下,因通信次数的增加,总的通信时间消耗将会变的不那么理想.同时,因为对依赖服务的线程池资源有限 ...
- spring cloud | Hystrix断路器是如何工作的
Hystrix是什么 Hystrix是一个java类库,提供了服务容错保护 遇到的问题 请求响应时间过长,造成资源不能被及时释放.短时巨量请求造成资源耗尽,最终造成系统无法响应. 系统中一个服务服务出 ...
- Spring Cloud Hystrix介绍
Hystrix 介绍 Hystrix [hɪst'rɪks],中文含义是豪猪,因其背上长满棘刺,从而拥有了自我保护的能力.SpringCloud Hystrix是Netflix开源的一款容错框架,具备 ...
- Spring cloud——Hystrix 原理解析
1.背景 分布式系统环境下,服务间类似依赖非常常见,一个业务调用通常依赖多个基础服务.如下图,对于同步调用,当库存服务不可用时,商品服务请求线程被阻塞,当有大批量请求调用库存服务时,最终可能导致整个商 ...
- Spring Cloud Hystrix 进行服务熔断设置时,报错找不到对应的服务熔断方法
问题描述:在进行服务熔断时出现 [Request processing failed; nested exception is com.netflix.hystrix.contrib.javanica ...
最新文章
- windows codeblocks clang 3.7.0
- VR开发从何入手的实战分享
- [Android1.6]继承BaseAdapter为GridView设置数据时设置setLayoutParams时注意
- mxnet基础到提高(7)--卷积神经网络基础(2)
- 使用 Tye 辅助开发 k8s 应用竟如此简单(六)
- 【TOJ1132】Square Root,二次同余方程
- java.sql.SQLSyntaxErrorException: Unknown column ‘###‘ in ‘field list‘
- Scala入门(一):直接在eclipse上安装Scala IDE
- 解决stackoverflow加载慢的插件
- 获取CPU序列号的Delphi程序
- 基于STM32的STM8脱机编程器源码分享
- 功能测试基础之业务流程测试
- 2019开发者调查报告出炉
- kali 安装volatility_Volatility取证使用笔记
- 主板各种插针接口与机箱(电源)的接法
- SQL代码建表时引用外键,有红线提示引用了无效的表
- NVML编译官方用例报错
- OpenCv初学者学习笔记(一):图像视频的加载与显示
- 《悟透JavaScript》之 甘露模型二
- 对于 C 源文件,IntelliSenseMode 已根据编译器参数和查询 compilerPath 从“windo