場(chǎng)景
Forest
聲明式HTTP客戶端API框架,讓Java發(fā)送HTTP/HTTPS請(qǐng)求不再難。它比OkHttp和HttpClient更高層,
是封裝調(diào)用第三方restful api client接口的好幫手,是retrofit和feign之外另一個(gè)選擇。
通過(guò)在接口上聲明注解的方式配置HTTP請(qǐng)求接口。
官網(wǎng):
Forest
?
代碼地址:
forest: 聲明式HTTP客戶端API框架,讓Java發(fā)送HTTP/HTTPS請(qǐng)求不再難。它比OkHttp和HttpClient更高層,是封裝調(diào)用第三方restful api client接口的好幫手,是retrofit和feign之外另一個(gè)選擇。通過(guò)在接口上聲明注解的方式配置HTTP請(qǐng)求接口
Forest的功能較多,下面記錄一個(gè)比較常用的功能,就是調(diào)用第三方api獲取數(shù)據(jù),并將json數(shù)據(jù)解析成對(duì)象。
注:
博客:
霸道流氓氣質(zhì)的博客_CSDN博客-C#,架構(gòu)之路,SpringBoot領(lǐng)域博主
實(shí)現(xiàn)
1、需要事先模擬一個(gè)第三方api的接口,各種方式均可,除了代碼編寫(xiě)、nginx代理等還可以使用如下方式
HTTP JSON接口模擬工具interfake的使用(模擬接口返回json數(shù)據(jù)):
HTTP JSON接口模擬工具interfake的使用(模擬接口返回json數(shù)據(jù))_霸道流氓氣質(zhì)的博客-CSDN博客
按照上面的過(guò)程并修改模擬數(shù)據(jù)的js文件內(nèi)容為
var Interfake = require('interfake');
var interfake = new Interfake();
interfake.get('/badao').status(200)
.body(
??? {?
??????? "id": 123,
??????? "name": "霸道的程序猿",
??????? "age": 100,
??????? "address":"青島",
??????? "banji":"一班"
??? }
);
interfake.get('/badaoStu').status(200)
.body(
??? {?
??????? "id": 123,
??????? "name": "霸道的程序猿",
??????? "age": 100,
??????? "address":"青島",
??????? "banji":"一班"
??? }
);
確保該接口可以用
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-440205.html
2、搭建SpringBoot項(xiàng)目
若依前后端分離版手把手教你本地搭建環(huán)境并運(yùn)行項(xiàng)目:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108465662?
在上面的基礎(chǔ)搭建之后,開(kāi)始集成Forest。
3、SpringBoot項(xiàng)目中添加依賴
??????? <dependency>
??????????? <groupId>com.dtflys.forest</groupId>
??????????? <artifactId>forest-spring-boot-starter</artifactId>
??????????? <version>1.5.30</version>
??????? </dependency>
當(dāng)前版本為1.5.30。
若依框架已經(jīng)自帶json數(shù)據(jù)的解析依賴。
然后修改配置文件yml,添加forest的相關(guān)配置
#Forest 全局配置
forest:
? backend: okhttp3???????????? # 后端HTTP框架(默認(rèn)為 okhttp3)
? max-connections: 1000??????? # 連接池最大連接數(shù)(默認(rèn)為 500)
? max-route-connections: 500?? # 每個(gè)路由的最大連接數(shù)(默認(rèn)為 500)
? max-request-queue-size: 100? # [自v1.5.22版本起可用] 最大請(qǐng)求等待隊(duì)列大小
? max-async-thread-size: 300?? # [自v1.5.21版本起可用] 最大異步線程數(shù)
? max-async-queue-size: 16???? # [自v1.5.22版本起可用] 最大異步線程池隊(duì)列大小
? timeout: 3000??????????????? # [已不推薦使用] 請(qǐng)求超時(shí)時(shí)間,單位為毫秒(默認(rèn)為 3000)
? connect-timeout: 3000??????? # 連接超時(shí)時(shí)間,單位為毫秒(默認(rèn)為 timeout)
? read-timeout: 3000?????????? # 數(shù)據(jù)讀取超時(shí)時(shí)間,單位為毫秒(默認(rèn)為 timeout)
? max-retry-count: 0?????????? # 請(qǐng)求失敗后重試次數(shù)(默認(rèn)為 0 次不重試)
? ssl-protocol: TLS??????????? # 單向驗(yàn)證的HTTPS的默認(rèn)TLS協(xié)議(默認(rèn)為 TLS)
? log-enabled: true??????????? # 打開(kāi)或關(guān)閉日志(默認(rèn)為 true)
? log-request: true??????????? # 打開(kāi)/關(guān)閉Forest請(qǐng)求日志(默認(rèn)為 true)
? log-response-status: true??? # 打開(kāi)/關(guān)閉Forest響應(yīng)狀態(tài)日志(默認(rèn)為 true)
? log-response-content: true?? # 打開(kāi)/關(guān)閉Forest響應(yīng)內(nèi)容日志(默認(rèn)為 false)
? async-mode: platform???????? # [自v1.5.27版本起可用] 異步模式(默認(rèn)為 platform)
更多詳細(xì)配置參考官方文檔
?? Springboot環(huán)境配置項(xiàng) | Forest
Forest 可以在forest.variables屬性下自定義全局變量。
其中 key 為變量名,value 為變量值。
全局變量可以在任何模板表達(dá)式中進(jìn)行數(shù)據(jù)綁定。
比如這里把第三方的api的ip和端口以及基礎(chǔ)地址等配置在yml中
?
#Forest 全局配置
forest:
? backend: okhttp3???????????? # 后端HTTP框架(默認(rèn)為 okhttp3)
? max-connections: 1000??????? # 連接池最大連接數(shù)(默認(rèn)為 500)
? max-route-connections: 500?? # 每個(gè)路由的最大連接數(shù)(默認(rèn)為 500)
? max-request-queue-size: 100? # [自v1.5.22版本起可用] 最大請(qǐng)求等待隊(duì)列大小
? max-async-thread-size: 300?? # [自v1.5.21版本起可用] 最大異步線程數(shù)
? max-async-queue-size: 16???? # [自v1.5.22版本起可用] 最大異步線程池隊(duì)列大小
? timeout: 3000??????????????? # [已不推薦使用] 請(qǐng)求超時(shí)時(shí)間,單位為毫秒(默認(rèn)為 3000)
? connect-timeout: 3000??????? # 連接超時(shí)時(shí)間,單位為毫秒(默認(rèn)為 timeout)
? read-timeout: 3000?????????? # 數(shù)據(jù)讀取超時(shí)時(shí)間,單位為毫秒(默認(rèn)為 timeout)
? max-retry-count: 0?????????? # 請(qǐng)求失敗后重試次數(shù)(默認(rèn)為 0 次不重試)
? ssl-protocol: TLS??????????? # 單向驗(yàn)證的HTTPS的默認(rèn)TLS協(xié)議(默認(rèn)為 TLS)
? log-enabled: true??????????? # 打開(kāi)或關(guān)閉日志(默認(rèn)為 true)
? log-request: true??????????? # 打開(kāi)/關(guān)閉Forest請(qǐng)求日志(默認(rèn)為 true)
? log-response-status: true??? # 打開(kāi)/關(guān)閉Forest響應(yīng)狀態(tài)日志(默認(rèn)為 true)
? log-response-content: true?? # 打開(kāi)/關(guān)閉Forest響應(yīng)內(nèi)容日志(默認(rèn)為 false)
? async-mode: platform???????? # [自v1.5.27版本起可用] 異步模式(默認(rèn)為 platform)
? #全局變量定義
? variables:
??? thirdApi:
????? baseUrl: http://127.0.0.1:666
?
4、創(chuàng)建一個(gè)Interface,比如這里叫IBusThirdApiService
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Get;
import com.ruoyi.system.domain.BusStudent;
import org.springframework.stereotype.Service;
@BaseRequest(baseURL = "${thirdApi.baseUrl}")
@Service
public interface IBusThirdApiService {
??? @Get("/badao")
??? String getData();
??? @Get("/badaoStu")
??? BusStudent getStudentData();
}
注意這里的
@BaseRequest(baseURL = "${thirdApi.baseUrl}")
就是設(shè)置該接口的基礎(chǔ)地址,這里是引用上面yml中配置的全局變量。
@Service
注入spring容器,可在需要的其他地方自動(dòng)注入。
通過(guò)@Get注解,將上面方法綁定了一個(gè) HTTP 請(qǐng)求, 并默認(rèn)使用GET方式,并創(chuàng)建兩個(gè)接口方法,
其中一個(gè)是返回字符串,一個(gè)是將json數(shù)據(jù)轉(zhuǎn)換成對(duì)象。
這里需要新建對(duì)象BusStudent
public class BusStudent extends BaseEntity
{
??? private static final long serialVersionUID = 1L;
??? /** id */
??? private Integer id;
??? /** 姓名 */
??? @Excel(name = "姓名")
??? private String name;
??? /** 年齡 */
??? @Excel(name = "年齡")
??? private Integer age;
??? /** 地址 */
??? @Excel(name = "地址")
??? private String address;
??? /** 班級(jí) */
??? @Excel(name = "班級(jí)")
??? private String banji;
??? public void setId(Integer id)
??? {
??????? this.id = id;
??? }
??? public Integer getId()
??? {
??????? return id;
??? }
??? public void setName(String name)
??? {
??????? this.name = name;
??? }
??? public String getName()
??? {
??????? return name;
??? }
??? public void setAge(Integer age)
??? {
??????? this.age = age;
??? }
??? public Integer getAge()
??? {
??????? return age;
??? }
??? public void setAddress(String address)
??? {
??????? this.address = address;
??? }
??? public String getAddress()
??? {
??????? return address;
??? }
??? public void setBanji(String banji)
??? {
??????? this.banji = banji;
??? }
??? public String getBanji()
??? {
??????? return banji;
??? }
??? @Override
??? public String toString() {
??????? return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
??????????? .append("id", getId())
??????????? .append("name", getName())
??????????? .append("age", getAge())
??????????? .append("address", getAddress())
??????????? .append("banji", getBanji())
??????????? .toString();
??? }
}
5、至此方法調(diào)用接口就完成了,注意這里版本是1.5.30,所以不用進(jìn)行掃描接口的配置,不用再修改啟動(dòng)類
?
然后便能在其他代碼中從 Spring 上下文注入接口實(shí)例,然后如調(diào)用普通接口那樣調(diào)用即可。
6、發(fā)送請(qǐng)求,這里模擬在定時(shí)任務(wù)中定時(shí)發(fā)起請(qǐng)求調(diào)用接口
import com.ruoyi.system.domain.BusStudent;
import com.ruoyi.system.service.IBusThirdApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@EnableScheduling
public class FurestTestTask {
??? @Autowired
??? private IBusThirdApiService iBusThirdApiService;
??? @Scheduled(fixedRateString = "5000")
??? public void taskGetData() {
??????? String data = iBusThirdApiService.getData();
??????? System.out.println("請(qǐng)求getData接口返回?cái)?shù)據(jù):"+data);
??????? BusStudent busStudent = iBusThirdApiService.getStudentData();
??????? System.out.println("請(qǐng)求getStudentData接口返回?cái)?shù)據(jù):"+busStudent);
??? }
}
運(yùn)行結(jié)果
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-440205.html
?
到了這里,關(guān)于Forest-聲明式HTTP客戶端框架-集成到SpringBoot實(shí)現(xiàn)調(diào)用第三方restful api并實(shí)現(xiàn)接口數(shù)據(jù)轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!