從零開始學springboot整合feign跨服務調(diào)用的方法
介紹
微服務橫行的互聯(lián)網(wǎng)世界, 跨服務調(diào)用顯得很平凡, 我們除了采用傳統(tǒng)的http方式接口調(diào)用, 有沒有更為優(yōu)雅方便的方法呢?
答案是肯定的,feign就提供了輕便的方式!
如果你的服務都注冊了注冊中心,比如nacos, 那么調(diào)用會顯得很輕松, 只需一個注解, 帶上需要調(diào)用的服務名即可,**feign + nacos
**會幫你做剩余的事.
如果沒有注冊中心, 也無需擔心, feign一樣可以以傳統(tǒng)的
ip:port
方式進行調(diào)用~
下面,我們來實踐下吧
springboot整合feign
引入依賴, 這里注意, spring-cloud.version記得要和spring-boot版本匹配, 我這里spring-boot版本是2.1.3, 所以spring-cloud選擇Greenwich.SR2版本.
大致的版本對應關系如下
更詳細的請去https://start.spring.io/actuator/info
查詢!
<properties> <spring-cloud.version>Greenwich.SR2</spring-cloud.version> </properties> <dependencyManagement> <dependencies> <!--SpringCloud依賴 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!--openfeign跨服務調(diào)用--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!--openfeign底層使用ApacheHttpClient調(diào)用--> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-httpclient</artifactId> </dependency> </dependencies>
然后我們?nèi)ロ椖康膯宇惿霞由献⒔?br />
@EnableFeignClients
最后, 加上Feign的配置
application.properties
server.port=9999 #******************openfeign配置,參數(shù)采用的是默認的配置,可根據(jù)實際情況調(diào)整*********************** #啟用ApacheHttpClient。默認就是true,使用HttpClientConnectionManager管理連接復用 feign.httpclient.enabled=true #連接池的最大連接數(shù),默認200 feign.httpclient.max-connections=200 #每個路由(服務器)分配的組最大連接數(shù),默認50 feign.httpclient.max-connections-per-route=50 #連接最大存活時間,默認900秒 feign.httpclient.time-to-live=900 #連接最大存活時間單位秒 feign.httpclient.time-to-live-unit=seconds #FeignAcceptGzipEncodingInterceptor攔截器被激活,會在header中添加Accept-Encoding:gzip,deflate,表明服務端在返回值時可以使用如下兩個方式壓縮返回結(jié)果 feign.compression.response.enabled=true #FeignContentGzipEncodingInterceptor攔截器被激活,會在header中添加Content-Encoding:gzip,deflate,表明body中的參數(shù)是使用這兩個方式的壓縮 feign.compression.request.enabled=true #content-length大于2048就進行請求參數(shù)的gzip壓縮 feign.compression.request.minRequestSize=2048 #開啟斷路器 feign.hystrix.enabled=true #斷路器的隔離策略,默認就是線程池,SEMAPHORE模式下,就是主線程調(diào)用的遠程的服務,即同步的 hystrix.command.default.execution.isolation.strategy=THREAD #斷路器超時設置 hystrix.command.default.execution.timeout.enabled=true #總體請求在45秒還是無法得到響應,建議觸發(fā)熔斷(ribbon每個請求讀取15秒超時,兩個實例重試就是30秒,openfeign外層默認會進行一次調(diào)用,4次重試) hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=45000 #斷路器的線程池存在一個問題,在隊列滿了以后,不會再去創(chuàng)建新的線程直到maximumSize #核心線程池大小 hystrix.threadpool.default.coreSize=10 #最大線程池大小 hystrix.threadpool.default.maximumSize=10 #超過這個空閑時間,多于coreSize數(shù)量的線程會被回收,1分鐘 hystrix.threadpool.default.keepAliveTimeMinutes=1 #隊列的大小,默認為-1,即沒有隊列 hystrix.threadpool.default.maxQueueSize=200 #隊列任務達到此閾值后,就開始拒絕;實際使用此參數(shù)進行隊列是否滿的判斷 hystrix.threadpool.default.queueSizeRejectionThreshold=180 #負載均衡配置 #讀取超時15秒,與原RestTemplate保持一致 ribbon.ReadTimeout=15000 #連接超時15秒,與原RestTemplate保持一致 ribbon.ConnectTimeout=15000 ##每臺服務器最多重試次數(shù),但是首次調(diào)用不包括在內(nèi) ribbon.MaxAutoRetries=0 ##最多重試多少臺服務器,與實際實例數(shù)保持一致(不包括首臺) ribbon.MaxAutoRetriesNextServer=1 #是否所有操作都重試, # false:get請求中,連接超時,讀取超時都會重試,其他請求(put,post)連接超時重試,讀取超時不重試。 # true:get請求中,連接超時,讀取超時都會重試,其他請求(put,post)連接超時重試,讀取超時重試。 #對于請求(put,post)要做好接口的冪等性 ribbon.OkToRetryOnAllOperations=true
spring-boot整合feign完成, 接下來我們編寫測試代碼
測試代碼
兩個服務
- sb-alibaba-nacos (被調(diào)用方服務, 127.0.0.1:8081), 提供 getInfoById接口
- sb-feign (調(diào)用方服務, 127.0.0.1:9999), 提供 getInfoById 測試接口
sb-alibaba-nacos提供的測試接口
@GetMapping(value = "getInfoById") public String getInfoById(@RequestParam(value = "id") Long Id) { return "example-service return :" + Id; }
sb-feign相關代碼
我們新建個包 feign,用來放所有涉及跨服務調(diào)用的類
ExampleControllerFeignClient.java:
package com.mrcoder.sbfeign.feign; import feign.hystrix.FallbackFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; @FeignClient(name = "sb-alibaba-nacos", url = "http://127.0.0.1:8081/", fallbackFactory = ExampleControllerFeignClient.ExampleControllerFeignClientFallbackFactory.class) public interface ExampleControllerFeignClient { @GetMapping(value = "getInfoById") String getInfoById(@RequestParam(value = "id") Long Id); /** * 服務降級內(nèi)部類 */ @Component class ExampleControllerFeignClientFallbackFactory implements FallbackFactory<ExampleControllerFeignClient> { private Logger logger = LoggerFactory.getLogger(ExampleControllerFeignClientFallbackFactory.class); @Override public ExampleControllerFeignClient create(Throwable cause) { return new ExampleControllerFeignClient() { @Override public String getInfoById(Long signingLogId) { logger.error("跨服務調(diào)用失敗, 原因是:" + cause.getMessage()); return "失敗, 原因是:" + cause.getMessage(); } }; } } }
關鍵代碼就是
@FeignClient(name = "sb-alibaba-nacos", url = "http://127.0.0.1:8081/", fallbackFactory = ExampleControllerFeignClient.ExampleControllerFeignClientFallbackFactory.class)
- name 就是被調(diào)用方的服務名稱 (
這里如果你沒有配置服務注冊中心的化,其實可以隨便寫
) - url 就是被調(diào)用方的地址(
如果配置了服務注冊中心, 可以不寫!, 不過兩個服務必須都注冊!,這樣才能找到!
) - fallbackFactory 就是調(diào)用失敗時指定的處理類
最后, 我們寫個測試方法
package com.mrcoder.sbfeign.controller; import com.mrcoder.sbfeign.feign.ExampleControllerFeignClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @CrossOrigin @RestController public class TestController { @Autowired private ExampleControllerFeignClient exampleControllerFeignClient; @RequestMapping(value = "getInfoById", method = RequestMethod.GET) public String test(@RequestParam(value = "id") Long Id) { return exampleControllerFeignClient.getInfoById(Id); } }
開啟兩個服務sb-alibaba-nacos, sb-feign
而后訪問sb-feign的測試方法
http://localhost:9999/getInfoById?id=22
出現(xiàn)
sb-alibaba-nacos return :22
跨服務調(diào)用成功~
到此這篇關于從零開始學springboot整合feign跨服務調(diào)用的文章就介紹到這了,更多相關springboot整合feign跨服務調(diào)用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解SpringBoot中的tomcat優(yōu)化和修改
這篇文章主要介紹了詳解SpringBoot中的tomcat優(yōu)化和修改,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09Gradle build 報錯:Received status code 400 from server
這篇文章主要介紹了Gradle build 報錯:Received status code 400 from server,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07springboot+zookeeper實現(xiàn)分布式鎖的示例代碼
本文主要介紹了springboot+zookeeper實現(xiàn)分布式鎖的示例代碼,文中根據(jù)實例編碼詳細介紹的十分詳盡,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03Java運行時環(huán)境之ClassLoader類加載機制詳解
這篇文章主要給大家介紹了關于Java運行時環(huán)境之ClassLoader類加載機制的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-01-01Java實現(xiàn)PDF轉(zhuǎn)圖片的三種方法
有些時候我們需要在項目中展示PDF,所以我們可以將PDF轉(zhuǎn)為圖片,然后已圖片的方式展示,效果很好,Java使用各種技術將pdf轉(zhuǎn)換成圖片格式,并且內(nèi)容不失幀,本文給大家介紹了三種方法實現(xiàn)PDF轉(zhuǎn)圖片的案例,需要的朋友可以參考下2023-10-10細數(shù)java中Long與Integer比較容易犯的錯誤總結(jié)
下面小編就為大家?guī)硪黄殧?shù)java中Long與Integer比較容易犯的錯誤總結(jié)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01基于java file 文件操作operate file of java的應用
本篇文章介紹了,基于java file 文件操作operate file of java的應用。需要的朋友參考下2013-05-05