Hystrix实现容错
增加hystrix依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
代码
public List findFallback() {
return Lists.newArrayList("fall back");
}
@HystrixCommand(fallbackMethod = "findFallback")
@PostMapping("/movie")
public List find() {
return restTemplate.postForObject("http://microservice-provider-user/api/user", null, List.class);
}
启用Hystrix
启动类增加 @EnableHystrix
注解
测试
启动服务正常返回结果,关闭microservice-provider-user服务,再次调用返回[fall back]
feign使用Hystrix
SpringCloud默认已为Feign整合了Hystrix,下面实现Feign回退:
@Component
public class FeignClientFallBack implements UserFeignClient {
@Override
public String find() {
return "fall back";
}
}
@FeignClient(name = "microservice-provider-user"
fallback = FeignClientFallBack.class)
public interface UserFeignClient {
@PostMapping("/api/user")
String find();
}
增加feign hystrix配置:
feign:
hystrix:
enabled: true