Spring Cloud --- Hystrix(容错工具)
发布日期:2021-05-20 01:12:06 浏览次数:17 分类:精选文章

本文共 6724 字,大约阅读时间需要 22 分钟。

Hystrix 解析

1. Hystrix 断路器

1.1 微服务宕机时,ribbon 无法转发请求

关闭 user-serviceorder-service

图片描述:79253124f84b080b945e0bad.jpg

1.2 项目创建

复制 sp06-ribbon 项目至 sp07-hystrix,关闭原项目。

图片描述:a70143563e516277aecf4a5.jpg

1.2.1 pom.xml 修改

添加 Spring Cloud Netlix Hystrix 依赖。

图片描述:b0084b145da1f621b293e5ec.jpg

1.2.2 application.yml 配置

添加 Hystrix 配置,启用断路器。

图片描述:c9014cc5d5d72f5db6b2c56.jpg

1.2.3 主程序注解

使用 @EnableCircuitBreaker 启用断路器。

代码示例

package cn.tedu.sp07;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
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;
@SpringBootApplication
@EnableCircuitBreaker
@EnableDiscoveryClient
public class Sp07HystrixApplication {
public static void main(String[] args) {
SpringApplication.run(Sp07HystrixApplication.class, args);
}
@LoadBalanced
@Bean
public RestTemplate getRestTemplate() {
SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
f.setConnectTimeout(1000);
f.setReadTimeout(1000);
return new RestTemplate(f);
}
}

1.3 HystrixController 降级方法

添加 @HystrixCommand 注解并实现降级方法。

代码示例

package cn.tedu.sp07.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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
@RestController
public class HystrixController {
@Autowired
private RestTemplate rt;
@GetMapping("/item-service/{orderId}")
@HystrixCommand(fallbackMethod = "getItemsFB")
public JsonResult
> getItems(@PathVariable String orderId) {
return rt.getForObject("http://item-service/{1}", JsonResult.class, orderId);
}
@PostMapping("/item-service/decreaseNumber")
@HystrixCommand(fallbackMethod = "decreaseNumberFB")
public JsonResult decreaseNumber(@RequestBody List
items) {
return rt.postForObject("http://item-service/decreaseNumber", items, JsonResult.class);
}
@GetMapping("/user-service/{userId}")
@HystrixCommand(fallbackMethod = "getUserFB")
public JsonResult
getUser(@PathVariable Integer userId) {
return rt.getForObject("http://user-service/{1}", JsonResult.class, userId);
}
@GetMapping("/user-service/{userId}/score")
@HystrixCommand(fallbackMethod = "addScoreFB")
public JsonResult addScore(@PathVariable Integer userId, Integer score) {
return rt.getForObject("http://user-service/{1}/score?score={2}", Paginator.class, userId, score);
}
@GetMapping("/order-service/{orderId}")
@HystrixCommand(fallbackMethod = "getOrderFB")
public JsonResult
getOrder(@PathVariable String orderId) {
return rt.getForObject("http://order-service/{1}", Paginator.class, orderId);
}
@GetMapping("/order-service")
@HystrixCommand(fallbackMethod = "addOrderFB")
public JsonResult addOrder() {
return rt.getForObject("http://order-service/", Paginator.class);
}
@HystrixCommand(fallbackMethod = "getItemsFB")
public JsonResult getItemsFB(String orderId) {
return JsonResult.err().msg("获取订单商品列表失败");
}
@HystrixCommand(fallbackMethod = "decreaseNumberFB")
public JsonResult decreaseNumberFB(List
items) { return JsonResult.err().msg("更新商品库存失败"); } @HystrixCommand(fallbackMethod = "getUserFB") public JsonResult getUserFB(Integer userId) { return JsonResult.err().msg("获取用户信息失败"); } @HystrixCommand(fallbackMethod = "addScoreFB") public JsonResult addScoreFB(Integer userId, Integer score) { return JsonResult.err().msg("增加用户积分失败"); } @HystrixCommand(fallbackMethod = "getOrderFB") public JsonResult getOrderFB(String orderId) { return JsonResult.err().msg("获取订单失败"); } @HystrixCommand(fallbackMethod = "addOrderFB") public JsonResult addOrderFB() { return JsonResult.err().msg("添加订单失败"); } }

1.4 Hystrix 超时设置

默认超时为1000ms,建议设置为10秒。

代码示例

spring:
application:
name: hystrix
server:
port: 3001
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
MaxAutoRetriesNextServer: 2
MaxAutoRetries: 1
OkToRetryOnAllOperations: true
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 500

1.5 访问测试

  • 检查 item-service 超时失败。
  • 检查 user-service 未启动。
  • 观察断路器状态。

图片描述:多个断路器测试图示。

2. Hystrix 电路板仪表盘

2.1 项目添加 Actuator

添加 Actuator 依赖并配置暴露端点。

代码示例

org.springframework.boot
spring-boot-starter-actuator

2.1.1 application.yml 配置

暴露 hystrix.stream 端点。

代码示例

spring:
application:
name: hystrix
server:
port: 3002
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
MaxAutoRetriesNextServer: 1
MaxAutoRetries: 1
OkToRetryOnAllOperations: true
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 500
management:
endpoints:
web:
exposure:
include: hystrix.stream

2.2 Hystrix 仪表盘

独立搭建仪表盘项目,配置监控路径。

代码示例

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;
@SpringBootApplication
@EnableHystrixDashboard
public class Sp08HystrixDashboardApplication {
public static void main(String[] args) {
SpringApplication.run(Sp08HystrixDashboardApplication.class, args);
}
}

2.3 测试

通过 ab 工具进行高并发测试,观察断路器状态。

命令示例

ab -n 20000 -c 50 http://localhost:3002/item-service/35

2.4 Hystrix 配置

调整配置参数以优化系统响应。

常用配置

  • hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
  • hystrix.command.default.circuitBreaker.requestVolumeThreshold
  • hystrix.command.default.circuitBreaker.errorThresholdPercentage
  • hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds

完整文档Hystrix官方文档

上一篇:Spring Cloud --- feign
下一篇:Spring Cloud Ribbon

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2025年05月04日 02时14分12秒