熔断配置
1、在order-service中pom文件中添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2、在OrderApplication中添加hystrix激活注解@EnableCircuitBreaker
3、在OrderController中添加如下代码
/**
* 使用注解配置熔断保护
* fallbackmethod : 配置熔断之后的降级方法
*/
@HystrixCommand(fallbackMethod = "orderFallBack")
@RequestMapping(value = "/buy/{id}",method = RequestMethod.GET)
public Product findById(@PathVariable Long id) {
Product product = productFeignClient.findById(id);
return product;
}
/**
* 降级方法
* 和需要收到保护的方法的返回值一致
* 方法参数一致
*/
public Product orderFallBack(Long id) {
Product product = new Product();
product.setProductName("触发降级方法");
return product;
}
4、在application.yml文件中添加如下配置
启动服务访问: http://localhost:9002/order/buy/1
这时停掉product服务再次访问 http://localhost:9002/order/buy/1
到这里我们的降级就基本实现了。
统一降级配置
@DefaultProperties(defaultFallback = “defaultFallBack”)*指定此接口中公共的熔断设置,如果过在@DefaultProperties指定了公共的降级方法,在@HystrixCommand**不需要单独指定了*
基于feign调用熔断配置
(1)修改order服务application.yml在Fegin中开启hystrix在Feign中已经内置了hystrix,但是默认是关闭的需要在工程的 application.yml 中开启对hystrix的支持(2)配置FeignClient接口的实现类基于Feign实现熔断降级,那么降级方法需要配置到FeignClient接口的实现类中
(3)修改FeignClient添加hystrix熔断在@FeignClient注解中添加降级方法@FeignClient注解中以fallback声明降级方法
feign:
hystrix: #在feign中开启hystrix熔断
enabled: true
重新启动order服务访问: http://localhost:9002/order/buy/1
hystrix监控数据
1、在order服务pom文件中添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2、在启动类加上注解
//激活hystrix
@EnableCircuitBreaker
3、在application.yml添加如下配置:
management:
endpoints:
web:
exposure:
include: '*'
访问: http://localhost:9002/actuator
在访问: http://localhost:9002/actuator/hystrix.stream
搭建Hystrix DashBoard监控
1、在order服务pom文件中添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
2、在启动类上添加注解@EnableHystrixDashboard
3、访问: http://localhost:9002/hystrix
断路器聚合监控Turbine
1、创建工程hystrix-turbine,引入相关依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-turbine</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>
2、配置多个微服务的hystrix监控
server:
port: 8031
spring:
application:
name: microservice-hystrix-turbine
eureka:
client:
service-url:
defaultZone: http://localhost:9000/eureka/
instance:
prefer-ip-address: true
turbine:
# 要监控的微服务列表,多个用,分隔
appConfig: order-service
clusterNameExpression: "'default'"
3、启动类:
@SpringBootApplication
@EnableTurbine
@EnableHystrixDashboard
public class TurbineAppcation {
public static void main(String[] args) {
SpringApplication.run(TurbineAppcation.class, args);
}
}
4、访问 http://localhost:8031/hystrix/