什么是Hystrix
在前边文章中我们微服务之间通信都是采用RestTemplate+Ribbon或者Feign来完成,但是有可能我们部署环境中会有各种问题,比如网络异常,如果其中一个服务异常,那么就会导致调用的的消费者进入网络阻塞,久而久之将会耗尽我们系统资源,导致崩溃,基于此,业界内提出了熔断器的概念,我们可以把它理解为一根保险丝,过热就会导致直接跳闸,当然我们不能让我们的服务器直接关机,而是通过其他方式来解决,例如返回一个固定值,当然Hystrix也提供了服务监控。
简而言之,Hystrix做了两件事,服务熔断,服务监控。
服务熔断
假如我们service B现在响应时间过长例如10s,或者根本不可调用,那么将会导致他的消费者进入长时间的等待,那么Hystrix就可以进行监控一旦触发阈值即执行Fallback方法。而@HystrixCommand就是我们要使用的注解。
案例demo
1.创建Hystrix模块,
2.添加依赖
<dependencies>
<dependency>
<groupId>com.study</groupId>
<artifactId>springCloudApi</artifactId>
<version>${project.version}</version>
</dependency>
<!--springboot web启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis 启动器-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>com.study</groupId>
<artifactId>springCloudApi</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!--添加eureka客户端依赖-->
<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>
</dependencies>
2.配置yml文件
server:
port: 8001
mybatis:
config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置文件所在路径
type-aliases-package: com.study.springCloud.entities # 所有Entity别名类所在包
mapper-locations: classpath:mybatis/mapper/**/*.xml # mapper映射文件
spring:
application:
name: provider #这个很重要,这在以后的服务与服务之间相互调用一般都是根据这个
datasource:
type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型
driver-class-name: com.mysql.cj.jdbc.Driver # mysql驱动包
url: jdbc:mysql://127.0.0.1:3306/springcloud?serverTimezone=GMT%2B8 # 数据库名称
username: root
password: 123
dbcp2:
min-idle: 5 # 数据库连接池的最小维持连接数
initial-size: 5 # 初始化连接数
max-total: 5 # 最大连接数
max-wait-millis: 150 # 等待连接获取的最大超时时间
eureka:
client:
registerWithEureka: true # 服务注册开关
fetchRegistry: true # 服务发现开关
serviceUrl: # 注册到哪一个Eureka Server服务注册中心,多个中间用逗号分隔
defaultZone: http://eureka6001.com:6001/eureka,http://eureka6002.com:6002/eureka
instance:
instanceId: ${spring.application.name}:${server.port}-hystrix
prefer-ip-address: true # 指定实例ID,就不会显示主机名了
3.修改我们之前创建的生产者的controller
可以看到我们添加了HystrixCommand注解,并添加了一个fallback方法。当熔断器触发时就将会调用fallback方法
package com.study.hystrix.controller;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import com.study.hystrix.service.ProductService;
import com.study.springCloud.entities.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author 王振读
* @date 2019/10/21 23:48
*/
@RestController
public class ProductController {
@Autowired
private ProductService productService;
@RequestMapping(value = "/product/add", method = RequestMethod.POST)
public boolean add(@RequestBody Product product) {
return productService.add(product);
}
@HystrixCommand(fallbackMethod = "getFallBack")
@RequestMapping(value = "/product/get/{id}", method = RequestMethod.GET)
public Product get(@PathVariable("id") Long id) {
Product product = productService.get(id);
if(product == null){
throw new RuntimeException("ID无效");
}
return product;
}
@RequestMapping(value = "/product/list", method = RequestMethod.GET)
public List<Product> list() {
return productService.list();
}
public Product getFallBack(@PathVariable("id") Long id) {
return new Product(id, id+"不正确","");
}
}
4.最后一步修改启动类
package com.study.hystrix;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
/**
* @author 王振读
* @date 2019/10/21 23:50
*/
@EnableHystrix
@EnableEurekaClient
@MapperScan("com.study.hystrix.mapper")
@SpringBootApplication
public class ProviderHystrixStart {
public static void main(String[] args) {
SpringApplication.run(ProviderHystrixStart.class, args);
}
@Bean
public ServletRegistrationBean hystrixMetricsStreamServlet() {
ServletRegistrationBean registration = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
registration.addUrlMappings("/actuator/hystrix.stream");
return registration;
}
}
测试
我们可以查询一个不存在的Id,那么程序就将会自动进入到fallback方法中。
消费者熔断
上边我们是通过提供者进行的熔断控制, 那么我们能否通过消费者就实现熔断控制呢?
Feign 是自带断路器的,也就是针对 消费者(客户端)进行服务熔断,需要在配置文件中开启它,在配置文件加以下代码:
#需要开启 hystric
feign:
hystrix:
enabled: true
在我们的@FeignClient注解中添加fallback 属性,并指定一个类
@FeignClient(value = "provider", fallback = HtristrixCallBack.class)
最后使我们定义的HtristrixCallBack类去实现我们的接口即可
package com.study.customerFeign.service;
import com.study.springCloud.entities.Product;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.ArrayList;
import java.util.List;
/**
* @author 王振读
* @date 2019/10/23 22:45
*/
@Component
public class HtristrixCallBack implements ProductService {
@Override
public boolean add(Product product) {
return false;
}
@Override
public Product get(Long id) {
return new Product(id,"不正确","");
}
@Override
public List<Product> list() {
return new ArrayList<>();
}
}
这样客户端的熔断配置就算完成了,当我们客户端的HysTrix触发后就会执行我们的实现类对应方法。
服务监控
HysTrix除了隔离依赖服务以外,它还提供了准实时的监控,他能够监控所有通过hystrix发起的请求,统计数据,并展示给运维人员。
案例
1.创建hystricxDashboard项目,并添加项目依赖。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springCloudParent</artifactId>
<groupId>com.study</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>hystricxDashboard</artifactId>
<dependencies>
<dependency>
<groupId>com.study</groupId>
<artifactId>springCloudApi</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--导入 hystrix 与 hystrix-dashboard 依赖-->
<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>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</project>
2.配置application.yml
server:
port: 9001
# 在被监控服务上添加暴露端点
management:
endpoints:
web:
exposure:
include: hystrix.stream
3.为要被监控的服务添加依赖,并配置气application.yml
<!--监控依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--已经存在 ,则不重复添加-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
# 在被监控服务上添加暴露端点
management:hystricxDashboard
endpoints:
web:
exposure:
include: hystrix.stream
监控测试
- 启动监控服务:
- 启动Eureka
- 启动被监控服务
正常启动监控服务访问后(地址:http://ip:port/hystr)如下页面即表示监控开启成功
然后我们在访问被监控者,地址:http://ip:port/actuator/hystrix.stream会看到如下页面
如果页面中只有ping没关系,你访问两次就有数据了,
然后我们将该地址填写在我们上一步的页面中,title随意,即可查看监控了。
下面是页面的详细说明