在前面Feign整合Ribbon负载均衡的基础上(Feign整合Ribbon负载均衡),Feigin再整合Hystrix断路
一、backend_show_consumer工程
该工程的依赖如下
1、工程中的application.yml中增加配置
feign: hystrix: enabled: true
2、增加接口ProviderApi,对应backend_show_provider中的提供的两个接口
@FeignClient(name = "hello-service-provider", path = "/provider", fallback = ProviderFallbackAPIImpl.class public interface ProviderApi { @RequestMapping(value = "/sayhello") String invokerProviderController(@RequestParam("message")String message); @RequestMapping(value = "/{providerId}/sayhello", method = RequestMethod.POST) String invokerProvider( @RequestHeader("author") String author, @PathVariable("providerId") String providerId, @RequestBody UserModel json); }
设置fallback = ProviderFallbackAPIImpl.class
3、降级实现:ProviderFallbackAPIImpl类
//降级实现 @Component public class ProviderFallbackAPIImpl implements ProviderApi { @Override public String invokerProviderController(String message) { return "invokerProviderController fallback message=" +message; } @Override public String invokerProvider(String author, String providerId, UserModel json) { return "invokerProvider fallback auth=" +author + ",providerId=" + providerId +",json=" +json; }
4、Controller方法
@Slf4j @RestController public class ConsumerController { @Resource private ConsumerServiceAPI serviceAPI; @Resource private ProviderApi providerApi; @RequestMapping(value = "/sayhello/feign") public String sayHelloFeign(String message){ System.out.println("feign message=" + message); return providerApi.invokerProviderController(message); } @RequestMapping(value = "/sayhello/post") public String sayHelloPost( String author, String providerId, UserModel json){ log.info("author:{},providerId;{}, userModel:{}", author, providerId, json); return providerApi.invokerProvider(author, providerId, json); } @RequestMapping(value = "/sayhello") public String sayHello(String message){ return serviceAPI.sayHello(message); } }
二、启动eureka服务(略)
三、启动backend_show_provider
四、测试
1、此时访问正常
或者
此时说明Feign整合Ribbon负载均衡器
2、停止backend_show_provider服务,这样backend_show_customer访问backend_show_provider就会超时,触发熔断
此时说明Feign整合Hystrix断路器
五、另外一种实现方式fallbackFactory
1、增加fallbackFactory配置
2、FallbackFactory 实现如下
@Component public class FallbackFactory implements feign.hystrix.FallbackFactory { @Override public ProviderApi create(Throwable throwable) { return new ProviderApi() { @Override public String invokerProviderController(String message) { return "invokerProviderController FallbackFactory message=" +message; } @Override public String invokerProvider(String author, String providerId, UserModel json) { return "invokerProvider FallbackFactory auth=" +author + ",providerId=" + providerId +",json=" +json; } }; } }
3、调用