Spring Cloud Feign 整合 Hystrix
在前面随笔Spring Cloud 之 Feign的feign工程基础上进行改造
1.pom.xml依赖不变
2.application.yml文件添加feign.hystrix.enabled=true开启Hystrix断路器,即:
spring: application: name: feign server: port: 8766 eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ feign: hystrix: enabled: true
3.新建Feign Hystrix 调用失败的回调类HystrixErrorFallBack
package com.dzpykj.hystrixService; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.dzpykj.feignInterface.HelloInterface; @Component public class HystrixErrorFallBack implements HelloInterface { @Value("${server.port}") String port; @Override public String hello(String name) { return "Sorry "+name+",when you are visting feign hystrix project,port:"+port+",you meet an error"; } }
4.在@FeignClient接口加入fallback回调类
package com.dzpykj.feignInterface; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.dzpykj.hystrixService.HystrixErrorFallBack; @FeignClient(value = "eurekaclient",fallback = HystrixErrorFallBack.class) //value为要负载均衡的spring.application.name public interface HelloInterface { @RequestMapping("/hi") //负载均衡目标工程里面的哪个方法 public String hello(@RequestParam(value="name") String name); }
5.依次启动Eureka服务集群、Eureka单个客户端、Feign工程
5.1 按照Spring Cloud Eureka Server集群Demo级搭建的步骤启动Eureka服务peer1,peer2集群
5.2按照Spring Cloud Eureka服务Demo级搭建启动8763的Eureka客户端
5.3启动Feign工程
6.访问 http://localhost:8766/hello/chaixy
7.模拟eurekaclient服务异常:手动将eurekaclient服务关闭,再次访问 http://localhost:8766/hello/chaixy
可以看到,当eurekaclient服务关闭时,访问遇到异常,回调了异常回调类HystrixErrorFallBack