ps:Fegin和Ribbon 其實是差不多的東西,Fegin里面也是集成了Ribbon,不過咱們寫代碼不是要優雅嘛,使用Feign就會優雅很多了,看著比直接使用Ribbon舒坦一點
就不重新構建項目了,實在懶得動手可以從git上把我的代碼拉去跑一跑,保證能運行。
1.首先在order_server里面引入對Fegin的依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
2.在啟動類中增加注解@EnableFeginClients

3.可以開始編寫咱們的Fegin代碼了
package net.xdclass.order_server.service; import net.xdclass.order_server.fallback.ProductClientFallback; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; /** * @date 2021/6/2 23:30 */ //寫上服務提供方的服務名稱 @FeignClient(value = "product-service") public interface ProductClient { //請注意,參數與被調用方實際接口一致 @GetMapping("/api/v1/product/findById") String findById(@RequestParam("id")int id); }
4.然后在需要調用接口的地方,注入這個Bean,ProductClient 再調用方法。
@Autowired private ProductClient productClient;
5.然后調用方法獲取返回值
6.設置負載均衡策略,在配置文件中增加以下配置,下面將默認的輪詢機制變更為隨機機制
product:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
7.fegin內置了hystrix,使用方式如下
feign: hystrix: #開啟熔斷器 enabled: true client: config: default: #連接超時時間 connectTimeout: 2000 #返回超時時間 readTimeout: 11000
8.加上fallback = ProductClientFallback.class
package net.xdclass.order_server.service; import net.xdclass.order_server.fallback.ProductClientFallback; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; /** * @author chengcheng123 * @date 2021/6/2 23:30 */ @FeignClient(value = "product-service",fallback = ProductClientFallback.class) public interface ProductClient { @GetMapping("/api/v1/product/findById") String findById(@RequestParam("id")int id); }
9.編寫ProductClientFallback,繼承使用fegin的productClient,然后將這個類用@component 標識為組件,交由IOC管理
/** * @date 2021/6/3 23:33 */ @Component public class ProductClientFallback implements ProductClient { @Override public String findById(int id) { System.out.println("feign 調用product-service findById 異常"); return null; } }
10.完事,自己驗證一下
怕什么真理無窮 進一寸有一寸的歡喜
浙公網安備 33010602011771號