以前工作的公司,也是用微服务架构,使用的是很简陋的自己封装的微服务框架,Apache CXF + Eureka,但没有实现服务降级和熔点的思想。一个典型的问题是,A服务依赖B服务,B服务依赖C服务,然而C服务因为数据库或其他原因的导致请求线程卡死,这样导致B服务等待C,A服务等待B,用户看到页面空白(A服务渲染)。这还不是最糟糕的,最糟糕的是并发量上去,C拖死B,B拖死A,A、B、C都死翘翘了,最后发现是DBServer的问题。很显然需要一个服务保护的工具,来解决这种异常超时等造成的服务雪崩效应。
Hystrix是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多依赖不可避免地回调用失败、超市、异常等,Hystrix能够保证一个依赖出问题的情况下,不会导致服务器的整体失败,避免级联故障,以提高分布式系统的健壮性。
1. 服务降级–Provider Demo
1.1 加入依赖到pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
1.2 配置application.yml
server:
port: 8001
spring:
application:
name: cloud-payment-hystrix-service
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka
1.3 主类配置注解
@EnableCircuitBreaker
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentHystrixApplication {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixApplication.class, args);
}
}
1.4 Controller & Service
PaymentController :
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {
@Autowired
private PaymentService paymentService;
@Value("${server.port}")
private int servicePort;
@GetMapping("/paymentInfoOK/{id}")
public String paymentInfoOK(@PathVariable("id") Integer id) {
String result = paymentService.paymentInfoOK(id);
log.info("+++++++ result: " + servicePort + result);
return result + servicePort;
}
@GetMapping("/paymentInfoTimeout/{id}")
public String paymentInfoTimeout(@PathVariable("id") Integer id) {
String result = paymentService.paymentInfoTimeout(id);
log.info("+++++++ result: " + servicePort + result);