Hystrix是Netflix的一个开源项目,它能够在依赖服务失效的情况下,通过隔离系统依赖服务的方式,防止服务级联失败;同时Hystrix提供失败回滚机制,使系统能够更快地从异常中恢复。
spring-cloud-netflix-hystrix对Hystrix进行封装和适配,使Hystrix能够更好地运行于Spring Cloud环境中,为微服务间的调用提供强有力的容错机制。
Hystrix具有如下的功能:
- 在通过第三方客户端访问(通常是通过网络)依赖服务出现高延迟或者失败时,为系统提供保护和控制。
- 在复杂的分布式系统中防止级联失败(服务雪崩效应)。
- 快速失败(Fail fast)同时能快速恢复。
- 提供失败回滚(Fallback)和优雅的服务降级机制。
- 提供近实时的监控、报警和运维控制手段。
Hystrix代码示例
本篇项目是在声明式客户端OpenFeign(一):基础应用的基础之上搭建。
在服务消费者control-personnel添加pom.xml依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
OpenFeign是自带Hystrix,但是默认没有打开,在application.yml中添加以下配置开启Hystrix:
feign:
hystrix:
enabled: true
在启动类中添加@EnableCircuitBreaker,开启Hystrix
package com.ljessie.controlpersonnel;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class ControlPersonnelApplication {
public static void main(String[] args) {
SpringApplication.run(ControlPersonnelApplication.class, args);
}
}
1.@HystrixCommand注解
TestController中,在testFeign()方法上添加@HystrixCommand注解,标注此方法开启断路器,失败回调方法为getMsgFailed()方法
@RestController
@RequestMapping("test")
public class TestController {
@Autowired
UserService userService;
@RequestMapping("test_feign")
@HystrixCommand(fallbackMethod = "getMsgFailed")
public String testFeign(String param){
return userService.testFeign(param);
}
public String getMsgFailed(String msg){
return "我是兜底数据!"+"参数:"+msg;
}
}
此时,只启动control-eureka-server和control-personnel。访问:http://localhost:8764/test/test_feign?param=Jessie
由于在testFeign()方法里面访问control-user服务失败,执行失败回滚方法,返回兜底数据。
2.Hystrix与OpenFeign
注掉TestController中testFeign()方法上的@HystrixCommand注解。
新建UserServiceCallback类,实现UserService接口:
package com.ljessie.controlpersonnel.service;
import com.ljessie.controlpersonnel.entity.User;
@Component
public class UserServiceCallback implements UserService{
@Override
public String testFeign(String param) {
return "UserServiceCallback------->我是兜底数据!"+"参数:"+param;
}
}
UserService中,@FeignClient注解添加fallback属性,指定访问失败时,执行的回调类。
由于此时Spring容器中有两个UserService组件,启动项目,会报UnsatisfiedDependencyException,因此在UserService类上添加@Primary注解,有其他组件依赖UserService时,指定使用UserService组件。
package com.ljessie.controlpersonnel.service;
import com.ljessie.controlpersonnel.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Primary
@FeignClient(value = "userServer",fallback = UserServiceCallback.class)
public interface UserService {
@RequestMapping("test/test_feign")
String testFeign(@RequestParam("param")String param);
}
结合OpenFeign.jpg
网友评论