系统容错工具html
降级java
熔断git
// 当调用远程服务失败,跳转到指定的方法,执行降级代码 @HystrixCommand(fallbackMethod="方法名") 远程调用方法() { restTemplate.getForObject(url,......); }
说明:这是没有hystrix的状况,下来测试hystrix提供的降级处理方式github
`<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>`
spring: application: name: hystrix server: port: 3001 eureka: client: service-url: defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka ribbon: MaxAutoRetries: 1 MaxAutoRetriesNextServer: 2 OkToRetryOnAllOperations: true
@EnableCircuitBreaker
启用 hystrix 断路器启动断路器,断路器提供两个核心功能:web
@SpringCloudApplication
注解代替三个注解package cn.tedu.sp06; import org.springframework.boot.SpringApplication; import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; //@EnableCircuitBreaker //@EnableDiscoveryClient //@SpringBootApplication @SpringCloudApplication public class Sp06RibbonApplication { @LoadBalanced @Bean public RestTemplate getRestTemplate() { SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory(); f.setConnectTimeout(1000); f.setReadTimeout(1000); return new RestTemplate(f); //RestTemplate 中默认的 Factory 实例中,两个超时属性默认是 -1, //未启用超时,也不会触发重试 //return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(Sp06RibbonApplication.class, args); } }
getItems()
添加降级方法 getItemsFB()
@HystrixCommand
注解,指定降级方法名package cn.tedu.sp06.controller; import cn.tedu.sp01.pojo.Item; import cn.tedu.sp01.pojo.Order; import cn.tedu.sp01.pojo.User; import cn.tedu.web.util.JsonResult; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.List; @RestController @Slf4j public class RibbonController { @Autowired private RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "getItemsFB") //指定降级方法的方法名 @GetMapping("/item-service/{orderId}") public JsonResult<List<Item>> getItems(@PathVariable String orderId){ //远程调用商品服务 //http://localhost:8001/{orderId} //{1} -- RestTemplate 定义的一种占位符格式,传递参数orderId //return restTemplate.getForObject("http://localhost:8001/{1}",JsonResult.class,orderId); return restTemplate.getForObject("http://item-service/{1}",JsonResult.class,orderId);//Ribbon的方式,将ip:port改成服务名称 } @HystrixCommand(fallbackMethod = "decreaseNumberFB") //指定降级方法的方法名 @PostMapping("/item-service/decreaseNumber") public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){ return restTemplate.postForObject("http://item-service/decreaseNumber", items, JsonResult.class); } // ----------------------- @HystrixCommand(fallbackMethod = "getUserFB") //指定降级方法的方法名 @GetMapping("/user-service/{userId}") public JsonResult<User> getUser(@PathVariable Integer userId){ return restTemplate.getForObject("http://user-service/{1}", JsonResult.class,userId); } @HystrixCommand(fallbackMethod = "addScoreFB") //指定降级方法的方法名 @GetMapping("/user-service/{userId}/score") public JsonResult<?> addScore(@PathVariable Integer userId,Integer score){ return restTemplate.getForObject("http://user-service/{1}/score?score={2}", JsonResult.class,userId,score); } @HystrixCommand(fallbackMethod = "getOrderFB") //指定降级方法的方法名 @GetMapping("/order-service/{orderId}") public JsonResult<Order> getOrder(@PathVariable String orderId){ return restTemplate.getForObject("http://order-service/{1}", JsonResult.class,orderId); } @HystrixCommand(fallbackMethod = "addOrderFB") //指定降级方法的方法名 @GetMapping("/order-service/") public JsonResult<?> addOrder(){ return restTemplate.getForObject("http://order-service/", JsonResult.class); } // ----------------------- //降级方法的参数和返回值,须要和原始方法一致,方法名任意 public JsonResult<List<Item>> getItemsFB(String orderId){ return JsonResult.err("获取订单商品列表失败"); } public JsonResult<?> decreaseNumberFB(List<Item> items){ return JsonResult.err("更新商品库存失败"); } public JsonResult<User> getUserFB(Integer userId){ return JsonResult.err("获取用户信息失败"); } public JsonResult<?> addScoreFB(Integer userId,Integer score){ return JsonResult.err("增长用户积分失败"); } public JsonResult<Order> getOrderFB(String orderId){ return JsonResult.err("获取订单失败"); } public JsonResult<?> addOrderFB(){ return JsonResult.err("添加订单失败"); } }
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
hystrix等待超时后, 会执行降级代码, 快速向客户端返回降级结果, 默认超时时间是1000毫秒
为了测试 hystrix 降级,咱们把 hystrix 等待超时设置得很是小(1000毫秒)
此设置通常应大于 ribbon 的重试超时时长,例如 10 秒spring
spring: application: name: hystrix server: port: 3001 eureka: client: service-url: defaultZone: http://eureka1:2001/eureka,http://eureka2:2002/eureka # 配置 Ribbon 重试次数 ribbon: # 次数参数没有提示,而且会有黄色警告 # 重试次数越少越好,通常建议用0 ,1 MaxAutoRetries: 1 MaxAutoRetriesNextServer: 2 #配置hystrix超时设置 快速向客户端返回降级结果, 默认超时时间是1000毫秒 hystrix: command: default: execution: isolation: thread: timeoutInMilliseconds: 1000
hystrix 对请求的降级和熔断,能够产生监控信息,hystrix dashboard能够实时的进行监控shell
springboot 提供的日志监控工具,能够暴露项目中多种监控信息apache
添加 actuatorwindows
yml 配置暴露监控数据缓存
actuator 是 spring boot 提供的服务监控工具,提供了各类监控信息的监控端点management.endpoints.web.exposure.include
配置选项,
能够指定端点名,来暴露监控端点
若是要暴露全部端点,能够用 “*”
右键点击项目或pom.xml, 编辑起步依赖, 添加 actuator 依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
hystrix.stream
监控端点spring: application: name: hystrix server: port: 3001 eureka: client: service-url: defaultZone: http://eureka1:2001/eureka,http://eureka2:2002/eureka # 配置 Ribbon 重试次数 ribbon: # 次数参数没有提示,而且会有黄色警告 # 重试次数越少越好,通常建议用0 ,1 MaxAutoRetries: 1 MaxAutoRetriesNextServer: 2 #配置hystrix超时设置 快速向客户端返回降级结果, 默认超时时间是1000毫秒 hystrix: command: default: execution: isolation: thread: timeoutInMilliseconds: 1000 #配置actuator,暴露hystrix.stream监控端点 management: endpoints: web: exposure: include: "*"
仪表盘项目能够是一个彻底独立的项目,与其余项目都无关,也不用向注册表注册
hystrix: dashboard: proxy-stream-allow-list: localhost
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>cn.tedu</groupId> <artifactId>sp08-hystrix-dashboard</artifactId> <version>0.0.1-SNAPSHOT</version> <name>sp08-hystrix-dashboard</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version> </properties> <dependencies> <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-dashboard</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
spring: application: name: hystrix-dashboard server: port: 4001 eureka: client: service-url: defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka hystrix: dashboard: proxy-stream-allow-list: localhost
@EnableHystrixDashboard
和 @EnableDiscoveryClient
package cn.tedu.sp08; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; @EnableDiscoveryClient @EnableHystrixDashboard @SpringBootApplication public class Sp08HystrixDashboardApplication { public static void main(String[] args) { SpringApplication.run(Sp08HystrixDashboardApplication.class, args); } }
http://localhost:3001/item-service/35
http://localhost:3001/user-service/7
http://localhost:3001/user-service/7/score?score=100
http://localhost:3001/order-service/123abc
http://localhost:3001/order-service/
短路器打开的条件:
短路器打开后,全部请求直接执行降级代码 断路器打开几秒后,会进入**半开状态**,客户端调用会尝试向后台服务发送一次调用, 若是调用成功,断路器能够自动关闭,恢复正常 若是调用仍然失败,继续保持打开状态几秒钟
整个链路达到必定的阈值,默认状况下,10秒内产生超过20次请求,则符合第一个条件。
知足第一个条件的状况下,若是请求的错误百分比大于阈值,则会打开断路器,默认为50%。
Hystrix的逻辑,先判断是否知足第一个条件,再判断第二个条件,若是两个条件都知足,则会开启断路器
断路器打开 5 秒后,会处于半开状态,会尝试转发请求,若是仍然失败,保持打开状态,若是成功,则关闭断路器
http://httpd.apache.org/docs/current/platform/windows.html#down
ab -n 20000 -c 50 http://localhost:3001/item-service/35
https://github.com/Netflix/Hystrix/wiki/Configuration
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
hystrix.command.default.circuitBreaker.requestVolumeThreshold
hystrix.command.default.circuitBreaker.errorThresholdPercentage
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds
断路器打开多长时间后,再次容许尝试访问(半开),仍失败则继续保持打开状态,如成功访问则关闭断路器,默认 5000