由于spring cloud的feign的依赖中已经包含了hystrix,所以feign在使用hystrix时,不需要添加hystrix的依赖。
只用添加feign的依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
spring boot启动类上也不需要使用@EnableCircuitBreaker注解,只用使用feign客户端的注解。
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class FeignWithHystrixApplication {
public static void main(String[] args) {
SpringApplication.run(FeignWithHystrixApplication.class, args);
}
}
在feign客户端的接口上的@FeignClient注解中,使用fallback属性指定降级类。
@FeignClient(name = "microservice-provider", fallback = HystrixClientFallback.class)
public interface MyFeignClient {
@RequestMapping(value = "/book/{id}", method = RequestMethod.GET)
public Book findById(@PathVariable("id") Long id);
}
降级回退类HystrixClientFallback要实现MyFeignClient 接口。
@Component
public class HystrixClientFallback implements MyFeignClient {
@Override
public Book findById(Long id) {
Book book = new Book();
book.setId(0L);
return book ;
}
}
也可以使用@FeignClient注解中的fallbackFactory属性指定降级回退工厂类,由工厂类来指定降级回退类。
@FeignClient(name = "microservice-provider", fallbackFactory = HystrixClientFactory.class)
public interface MyFeignClient {
@RequestMapping(value = "/book/{id}", method = RequestMethod.GET)
public Book findById(@PathVariable("id") Long id);
}
降级回退工厂类实现了FallbackFactory接口
@Component
public class HystrixClientFactory implements FallbackFactory<UserFeignClient> {
private static final Logger LOGGER = LoggerFactory.getLogger(HystrixClientFactory.class);
@Override
public MyFeignClient create(Throwable cause) {
HystrixClientFactory.LOGGER.info("fallback; reason was: {}", cause.getMessage());
return new MyFeignClientWithFactory() {
@Override
public Book findById(Long id) {
Book book = new Book();
book.setId(-1L);
return book ;
}
};
}
}
MyFeignClientWithFactory类要继承MyFeignClient 接口
public interface MyFeignClientWithFactory extends UserFeignClient {
}