1.首先在服务消费端引入Hystrix依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
2.启用Feign的Hystrix
feign:
hystrix:
enabled: true
3.修改feign接口,指定熔断处理类
@FeignClient(value = "service-helloworld",fallback = HelloApiFallback.class) public interface HelloApi { @RequestMapping(method = RequestMethod.GET, value = "/hello") public String sayHello(@RequestParam("name")String name); }
4.编写熔断实现类:HelloApiFallback
@Component public class HelloApiFallback implements HelloApi{ @Override public String sayHello(String name) { return "服务异常,启动熔断,HelloWorld"; } }
5.测试
分别启动注册中心,服务提供者,服务消费者,
在浏览器输入http://localhost:8120/hello?name=老王
可以看到会显示:
hello world ,老王
关掉服务提供者,再次访问上面地址,会显示:
服务异常,启动熔断,HelloWorld
表示,熔断已经生效。
再次启动服务提供者,访问http://localhost:8120/hello?name=老王
会显示:hello world ,老王
表示服务恢复后,熔断关闭。
6.关掉部分接口的熔断处理。
配置文件启动Hystrix后,Feign就会使用断路器包裹Feign客户端的所有方法。这样虽然方便,但是很多场景下并不需要该功能。
如果上面的api,去掉fallback 方法会报错。
错误如下:
There was an unexpected error (type=Internal Server Error, status=500).
HelloApi#sayHello(String) timed-out and no fallback available.
需要加下Hystrix配置,代码如下:
@Configuration public class FeignDisableHystrixConfiguration { @Bean @Scope("prototype") public Feign.Builder feignBuilder() { return Feign.builder(); } }
再在对应不需要实现熔断的地方指定该配置类
@FeignClient(value = "service-helloworld",configuration = FeignDisableHystrixConfiguration.class) public interface HelloApi { @RequestMapping(method = RequestMethod.GET, value = "/hello") public String sayHello(@RequestParam("name")String name); }
源码地址:
源码地址:https://gitee.com/zhuyuehua/springcloud_helloWorld