作者:jiangzz
电话:15652034180
微信:jiangzz_wx
微信公众账号:jiangzz_wy
Hystrix是一个延迟和容错库,旨在隔离对远程系统,服务和第三方库的访问点,停止级联故障,并在复杂的分布式系统中实现弹性,在这些系统中,故障是不可避免的。
引入以下依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
SpringBootApplication入口中需要添加@EnableCircuitBreaker
注解,此时Spring工厂会启动AOP方式对所有的方法上有@HystrixCommand
的业务方法添加熔断策略。
@SpringBootApplication
@EnableCircuitBreaker
@MapperScans(value = {@MapperScan(basePackages = {"com.jiangzz.dao"})})
public class HystrixSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixSpringBootApplication.class,args);
}
}
在业务方法上添加@HystrixCommand
注解实现熔断。
@HystrixCommand
@Override
public User queryUserById(Integer id) {
System.out.println(Thread.currentThread().getId());
return userDAO.queryById(id);
}
线程隔离
默认该方法的执行会启动新的线程执行和主程序不在一个线程中,因此如果上下文中存在ThreadLocal变量,在该方法中就失效了。因此一般可以通过设置commandProperties注解属性,设置线程就可以了。
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "execution.isolation.strategy",value = "SEMAPHORE")
})
@Override
public User queryUserById(Integer id) {
System.out.println(Thread.currentThread().getId());
return userDAO.queryById(id);
}
execution.isolation.strategy
该属性的可选值有两个THREAD
和SEMAPHORE
默认值是THREAD
.①一般如果一个实例一秒钟有100个并发,此时因为频繁启动线程的开销过大此时一般考虑使用SEMAPHORE,②非网络调用。
Fallback
过在@HystrixCommand中声明fallbackMethod的名称可以实现优雅降级,如下所示:
@HystrixCommand(fallbackMethod = "fallbackMethodQueryUserById")
@Override
public User queryUserById(Integer id) {
System.out.println(Thread.currentThread().getId());
int i=10/0;
return userDAO.queryById(id);
}
public User fallbackMethodQueryUserById(Integer id, Throwable e) {
System.out.println(e.getMessage());
return new User();
}
注意要求fallbackMethod方法和目标方法必须在同一个类中,具有相同的参数(异常参数可选)
Error Propagation
根据此描述,@ HystrixCommand能够指定应忽略的异常类型。如下所述ArithmeticException: / by zero
将不会触发fallbackMethod方法。
@HystrixCommand(fallbackMethod = "fallbackMethodQueryUserById",ignoreExceptions = {ArithmeticException.class})
@Override
public User queryUserById(Integer id) {
System.out.println(Thread.currentThread().getId());
int i=10/0;
return userDAO.queryById(id);
}
public User fallbackMethodQueryUserById(Integer id, Throwable e) {
System.out.println(e.getMessage());
return new User();
}
请求超时熔断
用户可以通过设置execution.isolation.thread.timeoutInMilliseconds
属性设置一个方法最大请求延迟,系统会抛出HystrixTimeoutException
@HystrixCommand(fallbackMethod = "fallbackMethodQueryUserById",commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="100")
})
@Override
public User queryUserById(Integer id) {
return userDAO.queryById(id);
}
public User fallbackMethodQueryUserById(Integer id, Throwable e) {
System.out.println(e);
return new User();
}
更多内容请参考:
https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica
https://github.com/Netflix/Hystrix/wiki/Configuration
Hystrix Dashboard
项目添加如下依赖
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
SpringBoot入口类添加@EnableHystrixDashboard
注解如下
@SpringBootApplication
@MapperScans(value = {@MapperScan(basePackages = {"com.jiangzz.dao"})})
@EnableCircuitBreaker
@EnableHystrixDashboard
public class SpringBootApplicationDemo {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplicationDemo.class,args);
}
}
修改application.properties配置文件如下
# 配置数据源
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springcloud?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
## MyBatis DAO
mybatis.type-aliases-package=com.jiangzz.entities
mybatis.mapper-locations=classpath*:mappers/*.xml
## 打印SQL
logging.level.root=info
logging.level.org.springframework.jdbc=debug
logging.level.com.jiangzz.dao=trace
spring.application.name=USER-SERVICE
eureka.instance.instance-id=001
eureka.instance.prefer-ip-address=true
eureka.instance.lease-expiration-duration-in-seconds=20
eureka.instance.lease-renewal-interval-in-seconds=10
eureka.client.register-with-eureka=true
eureka.client.healthcheck.enabled=true
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://jiangzz:123456@localhost:8761/eureka/
management.endpoints.web.exposure.include=*
修改UserService业务代码如下
@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class UserService implements IUserService {
@Autowired
private IUserDAO userDAO;
@HystrixCommand(fallbackMethod = "fallbackMethodQueryUserById",commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="100")
})
@Override
public User queryUserById(Integer id) {
return userDAO.queryById(id);
}
public User fallbackMethodQueryUserById(Integer id, Throwable e) {
System.out.println(e);
return new User();
}
}
访问页面http://localhost:8080/hystrix
点击 Monitor Stream
按钮查看监控状态