Fallback可以幫助我們在使用Feign去調用另外一個服務時,如果出現了問題,走服務降級,返回一個錯誤數據,避免功能因為一個服務出現問題,全部失效。
依賴:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
啟動類上添加注解:
//開啟Feign調用, 掃描feign接口所在包 @EnableFeignClients(basePackages = {"com.xx.feign"})
1。創建一個類,去實現自己的feign接口,並實現里面的方法,並用@Component交給spring管理
例如
/** * 當feign調用出問題了, 會自動執行這里, 防止調用報錯中斷執行 * 這里都是給feign調用的錯誤兜底的方法 * 注意: 兜底方法的路徑不能和feign接口相同, 因為springMvc不允許同一個訪問路徑有兩個方法 * @author zhaojian */ @Component @RequestMapping("/fallback") public class SearchFeignFallBack implements SearchFeign { @Override public String index() { return "feign調用出問題了"; } @Override public Customer findById(Integer id) { return new Customer(1, "feign調用有問題"); } @Override public Customer findCustomer(Integer id, String name) { return new Customer(1, "feign調用有問題"); } @Override public Customer save(Customer customer) { return new Customer(1, "feign調用有問題"); } }
修改之前自己寫的feign接口,在注解中,添加fallback類名.class
例如:
/** * feign接口, FeignClient后面指定被調用微服務的服務名 * @author zhaojian */ @FeignClient(value = "SEARCH", fallback = SearchFeignFallBack.class) @RestController public interface SearchFeign {
這個微服務的配置文件yml添加內容,如下:
server: port: 9001 #指定服務的名稱 spring: application: name: CUSTOMER # 指定Eureka服務地址 eureka: client: service-url: defaultZone: http://root:root@localhost:8761/eureka # 指定具體服務的負載均衡策略 SEARCH: ribbon: # 具體負載均衡使用的類 NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule feign: hystrix: enabled: true
然后再controller,用feign遠程調用出現問題時,會走剛才寫的fallback降級方法
