#Hystrix
一.Hystrix服务熔断
服务熔断,当此服务因为某种情况崩掉或者宕机时候,熔断此此服务,启用备用服务。
例子
- 创建springcloud(自己命名的项目)项目,创建module如下:
2. 项目结构图
在springcloud_pro_dept_hystrix_8001项目中引入Hystrix依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
使用hystrix只需要添加@HystrixCommand注解,在需要熔断的方法上加上此注解即可。
@GetMapping("/dept/get/{id}")
@HystrixCommand(fallbackMethod = "hystrixGet")//fallbackMethod是当get()方法失效时,调用备用hystrixGet方法
public Dept get(@PathVariable("id") Long id) {
Dept dept = deptService.queryDeptById(id);
if (dept == null) {
throw new RuntimeException("id" + id + ",不存在该用户");
}
return dept;
}
//hystrix熔断备选方法
public Dept hystrixGet(Long id) {
return new Dept().setDept_id(id).setDept_name("id" + id + ",不存在该用户,null").setDb_source("no database null");
}
在这之后,需要在该项目的主启动类上加上@EnableCircuitBreaker注解,使它能够找的熔断备选方法
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker//hystrix 断路注解
public class DeptPro_hystrix_8001 {
public static void main(String[] args) {
SpringApplication.run(DeptPro_hystrix_8001.class, args);
}
}
二.服务降级
服务降级:当某段时间某一项服务访问人数增多,而其他服务人数较少时候,客户端主动关闭服务人数较少的服务,为高并发的服务提供资源。
使用:
在客户端:springcloud_consumer_dept_8090中书写:
-
在api项目中添加服务降级的service,继承FallbackFactory
-
在客户服务端添加配置文件信息
feign: hystrix: enabled: true #开启服务降级
三.对比
名称 | 服务熔断 | 服务降级 |
---|---|---|
服务端,提供服务的那一端,属于被动使用,当服务宕机等情况发生,熔断,启用备用服务 | 客户端,属于主动使用,当某一个服务出现下高并发时候,关闭其他服务为该服务提供资源,此时使用服务降级,用户在客户端无法访问其他服务 |
四.Dashboard流监控
创建一个子项目springcloud_consumer_dashboard_8092
-
配置文件修改端口
server: port: 8092
-
添加主启动类并添加Dashboard的注解
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class}) @EnableHystrixDashboard public class DeptConsumerDashboard_8092 { public static void main(String[] args) { SpringApplication.run(DeptConsumerDashboard_8092.class, args); } }
-
在带有hystrix的服务端的主启动类添加servlet
@Bean public ServletRegistrationBean getServlet() { HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet(); ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet); registrationBean.setLoadOnStartup(1); registrationBean.addUrlMappings("/actuator/hystrix.stream"); registrationBean.setName("HystrixMetricsStreamServlet"); return registrationBean; }
-
其实看教程到这步就可以了,但是我的dashboard显示无法连接,所以需要在dashboard的配置文件上加上新的配置。
hystrix: dashboard: proxy-stream-allow-list: "localhost" #注明允许连接的名称。
配置了这个之后,dashboard就能识别并监控我们所需要监控的服务了。