1. 概述
本文主要包括如下内容:
- 1 通过@HystrixCommand注解实现在Spring Cloud中使用Hystrix组件:包括通过@HystrixCommand调用服务,实现fallback方法
- 2 如何通过配置自定义的Hystrix参数
- 3 对@HystrixCommand+@EnableCircuitBreaker的原理进行介绍
2. 通过@HystrixCommand注解实现在Spring Cloud使用Hystrix组件相关的工程
- cloud-registration-center:注册中心
- cloud-service-hystrix: 作为服务方的工程
- cloud-consumer-hystrix:通过hystrix调用cloud-service-hystrix的接口
3. cloud-registration-center
注册中心,此工程之前已经介绍过了,这里略
4. cloud-service-hystrix
作为服务方的工程,此工程比较简单,详细的创建方法见这节Spring cloud系列一 包含所有基本要素的完整Spring Cloud demo
其他和例子有关的配置如下:
4.1. bootstrap-hystrix.yml
只列出部分内容
spring:
application:
# 本服务注册到注册到服务器的名称, 这个名称就是后面调用服务时的服务标识符
name: cloud-hystrix-service
….
4.2. SimpleCtl:提供服务的Control类
@RestController
public class SimpleCtl {
private AtomicInteger count = new AtomicInteger();
private AtomicInteger sleepCount = new AtomicInteger();
@RequestMapping(value="/hystrix/simple")
public String hystrixClientCall(@RequestParam("time") long time){
int newCount = count.incrementAndGet();
return "time " + time + " hystrix" + newCount + ": " + ThreadLocalRandom.current().nextInt(1000);
}
……
}
5. cloud-consumer-hystrix
通过hystrix调用cloud-service-hystrix的接口
5.1. pom.xml:只列出关键的jar
<!-- hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
5.2. bootstrap-hystrix-simple.yml属性配置
# port
server:
port: 12083
spring:
application:
# 本服务注册到注册到服务器的名称, 这个名称就是后面调用服务时的服务标识符
name: cloud-consumer-hystrix
eureka:
client:
serviceUrl:
# 服务器注册/获取服务器的zone
defaultZone: http://127.0.0.1:10761/eureka/
instance:
prefer-ip-address: true
5.3. MyHystrixClient
功能:通过RestTemplate调用服务的接口
- @HystrixCommand:此注解表示此方法是hystrix方法,其中fallbackMethod定义回退方法的名称
- String myFallback(long p, Throwable e) :HystrixCommand的回退方法,此方法必须和hystrix的执行方法在相同类中。可以把HystrixCommand的执行参数和执行失败的异常传入回退方法中
@Service