很多文章整合的时候只演示了降级,没提到断路器,遂自己尝试了下
pom.xml 引入feign和hystrix的依赖。如果要使用断路器,需要依赖spring-cloud-starter-netflix-hystrix
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
编写FeignClient
@FeignClient(name = "test-manager", url = "${com.test.url}", fallback = TestFallback.class, path = "/test-manager")
public interface TestFeign {
@PostMapping(value = "/test/list")
List<TestDto> list(@RequestBody TestDto testDto);
}
这里可以使用PostMapping,应该是高版本修复了feign不支持PostMapping、GetMapping的方式?这里测试是Ok的。
name因为这里没有使用注册中心,所以name用不着,如果使用了注册中心(eureka或nacos),这里要填微服务名称,但是一定要配置否则启动报错。
url指定一个address:port,可以使用${}的方式从配置文件读取。
fallback指定一个服务降级类
path指定默认请求前缀,比如上面就是
${com.test.url} + path + 方法的@PostMapping的value
。
application.yaml
# 服务使用方的port
server:
port: 9086
# 服务提供方的机器ip+port
com:
test:
url: http://localhost:9085
# 一定要配置为true
feign:
hystrix:
enabled: true
降级类TestFallback
// @Service一定要有,也可以是@Component等模式注解
@Service
@Slf4j
public class TestFallback implements TestFeign {
@Override
public List<TestDto> list(TestDto testDto) {
log.error("调用接口失败 id = |{}|", testDto.getId());
return new ArrayList<>();
}
}
controller
@RestController
@RequestMapping("/test-app/test")
public class TestController {
@Autowired
private TestService testService;
@GetMapping("/test1")
public void test1() {
for (int i = 0; i < 15; i++) {
TestDto dto = new TestDto();
dto.setId(i);
testService.test(dto);
}
}
@GetMapping("/test2")
public void test2() {
for (int i = 15; i < 30; i++) {
TestDto dto = new TestDto();
dto.setId(i);
testService.test(dto);
}
}
}
先调用一下http://localhost:9086/test-app/test/test1/
,通的
现在关掉com.test.url提供的服务,再次访问
输出结果是每一秒打印一行,因为断路器默认是一秒后请求超时再执行降级方法。
接下来是断路器的测试
先在SpringBoot启动类上打上@EnableCircuitBreaker
注解
之前在controller里写了两个测试方法/test1
和/test2
,每个发送15次请求,按照断路器的默认配置,5s内失败请求失败20次则直接打开断路器,此时的请求直接走降级方法。
先访问/test1
再访问/test2
,看下打印结果
|0| 到|24|为前20次请求,交替打印。此时已经满足5s内失败20次请求,则此时断路器打开,不会等待超时一秒再进入降级,而是直接进入降级,所以后面的打印是连续的|10|到|14|和|25|到|29|