微服務之Feign的介紹與使用小結
前言:
最近在學習微服務相關的知識,看了黑馬的相關課程,將關于Feign的知識又總結了一些,希望能幫到各位小伙兒們以及加深下自己的印象??
??Feign的簡介
Feign 是一個聲明式的偽RPC的REST客戶端,它用了基于接口的注解方式,很方便的客戶端配置,Spring Cloud 給 Feign 添加了支持Spring MVC注解,并整合Ribbon及Eureka進行支持負載均衡。
Feign 是?個 HTTP 請求的輕量級客戶端框架。通過接?口和注解的?式發(fā)起 HTTP 請求調?,面向接口編程,并不是像 Java 中通過封裝 HTTP 請求報?的?式直接調?。
服務消費?拿到服務提供?的接?,然后像調?本地接??法?樣去調?,實際發(fā)出的是遠程的請求。讓我們更加便捷和優(yōu)雅的去調?基于 HTTP 的 API,被?泛應?在 Spring Cloud 的解決?案中。
??Feign的優(yōu)點
之前我們利用RestTemplate發(fā)起遠程調用的代碼:
String url = "http://userservice/user/" + order.getUserld(); User user = restTemplate.getForObject(url, User.class);
上面的存在的問題有代碼:
可讀性差,編程體驗不統(tǒng)一;
參數復雜URL難以維護
Feign是一個聲明式的http客戶端,官方地址:Feign官方鏈接
其作用就是幫助我們優(yōu)雅的實現http請求的發(fā)送,解決上面提到的問題。
??Feign如何使用
還是以我們之前的項目為例
在order-service服務的pom文件中引入feign依賴:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
在order-service的啟動類添加注解開啟Feign的功能:
@EnableFeignClients @MapperScan("cn.itcast.order,mapper") @SpringBootApplication public class OrderApplication public static void main(String[] args) [ SpringApplication.run(OrderApplication.class,args)
在order-service中新建一個接口,內容如下:
package cn.itcast.order.client;? import cn.itcast.order.pojo.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; ?@FeignClient("userservice") public interface UserClient { @GetMapping("/user/{id}") User findById(@PathVariable("id") Long id); }
這個客戶端主要是基于SpringMVC的注解來聲明遠程調用的信息,比如:
- 服務名稱:userservice
- 請求方式:GET
- 請求路徑:/user/{id}
- 請求參數:Long id
- 返回值類型:User
這樣,Feign就可以幫助我們發(fā)送http請求,無需自己使用RestTemplate來發(fā)送了。
我們修改order-service中的OrderService類中的queryOrderById方法,使用Feign客戶端代替RestTemplate:
@Autowired private UserClient userClient; public Order query0rderById(Long orderId) //1.查詢訂單 Order order = orderMapper.findById(orderId); //2. 利用Feign發(fā)起http請求 查詢用戶 Useruser = userClient.findById(order.getUserId()); //3.封裝user到0rder order.setUser(user); // 4.返回 return order;
??Feign的使用總結
使用Feign的步驟:
第①步 引入依賴
第②步 添加@EnableFeignClients注解
第③步 編寫FeignClient接口
第④步 使用FeignClient中定義的方法代替RestTemplate
到此這篇關于微服務之Feign的介紹與使用的文章就介紹到這了,更多相關微服務Feign內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
springboot配置多數據源(靜態(tài)和動態(tài)數據源)
在開發(fā)過程中,很多時候都會有垮數據庫操作數據的情況,需要同時配置多套數據源,本文主要介紹了springboot配置多數據源(靜態(tài)和動態(tài)數據源),感興趣的可以了解一下2023-09-09SpringBoot中的@EnableAutoConfiguration注解解析
這篇文章主要介紹了SpringBoot中的@EnableAutoConfiguration注解解析,@EnableAutoConfiguration也是借助@Import的幫助,將所有符合自動配置條件的bean定義注冊到IoC容器,需要的朋友可以參考下2023-09-09