前言
Thrift是RPC通信的一種方式,可以通過跨語言進行通信,最近項目需要進行跨語言的通信,因此首先嘗試搭建了一個簡單的thrift框架,因為網(wǎng)上的實例大都參差不全,通過gpt查詢得到的結(jié)果對我?guī)椭笠稽c,但是也不夠仔細,因此做此總結(jié),希望給需要的人幫助。
正文
1 創(chuàng)建一個gradle項目
首先我們需要創(chuàng)建一個gradle項目,如果你是在當前項目的基礎(chǔ)上也可以不做創(chuàng)建哦。
2 添加依賴
找到根目錄的bulid.gradle 文件添加依賴
ependencies {
implementation 'org.apache.thrift:libthrift:0.15.0'
}
之后idea會提示你導入依賴,或者收到更新一下依賴就可以生成thrift對應的依賴。
3創(chuàng)建一個簡單的demo
-
創(chuàng)建 .thrift文件
創(chuàng)建一個文件夾比如命名為thrift,在文件下創(chuàng)建一個.thrift文件,用于生成對應語言的代碼。
比如我創(chuàng)建了一個login.thrift 文件,添加兩個方法,一個有返回值,一個沒有返回值。
創(chuàng)建的文件↓:
文件內(nèi)容↓: -
通過命令生成對應的java接口代碼
這是thrift的一套機制,因為thrift是跨語言的,所以你要生成你的接口對應語言的service。
在你剛才創(chuàng)建的 .thrift文件所在的路徑下執(zhí)行命令。
找到你的 .thrift文件,右鍵,open in terminal,執(zhí)行命令
thrift --gen java loginService.thrift
其中 xx.thrift 就是你剛才創(chuàng)建的文件
(▽) 如果你發(fā)現(xiàn),這個命令沒辦法執(zhí)行,那你需要先執(zhí)行這個命令哦:(親測有效)
sudo zypper install thrift
他就會自動生成文件夾和文件↓
-
寫一個實現(xiàn)類,實現(xiàn)剛才生成的接口
針對你需要的功能,寫一個實現(xiàn)類,比如我寫一個loginServiceImpl,實現(xiàn)剛才生成的接口類。
到現(xiàn)在為止,我們已經(jīng)完成了大部分,之后我們就開始寫一個服務端和一個客戶端去測試了。thrfit需要創(chuàng)建一個server端和一個client端,用于我們發(fā)送通信和接收通信。文章來源:http://www.zghlxwxcb.cn/news/detail-671053.html -
寫服務端
創(chuàng)建一個thriftServer,類你可以隨意命名。舉例↓文章來源地址http://www.zghlxwxcb.cn/news/detail-671053.html
package com.gehc.surgery.thrift.Server;
import com.gehc.surgery.thrift.loginServiceImpl;
import com.gehc.surgery.thrift.loginService;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
public class ThriftServer {
public static void main(String[] args){
try {
//剛才自己創(chuàng)建的實現(xiàn)類
loginServiceImpl login =new loginServiceImpl();
TServerSocket serverSocket =new TServerSocket(9090);
loginService.Processor<loginServiceImpl> processor =new loginService.Processor<>(login);
TServer.Args serverArg =new TServer.Args(serverSocket);
serverArg.processor(processor);
TSimpleServer server =new TSimpleServer(serverArg);
server.serve();
}catch (Exception e){
e.printStackTrace();
}
}
}
- 寫一個客戶端
創(chuàng)建一個thriftClient類,類名你可以自己命名,寫法如下↓:
package com.gehc.surgery.thrift.Client;
import com.gehc.surgery.thrift.loginService;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
public class ThriftClient {
public static void main(String[] args) throws TException {
//自己定一下ip和端口 我隨意定義的
TTransport transport= new TSocket("localhost",9090);
transport.open();
TBinaryProtocol protocol=new TBinaryProtocol(transport);
loginService.Client client=new loginService.Client(protocol);
//你的實現(xiàn)類的方法
client.login();
boolean result= client.login1();
System.out.println(result);
transport.close();
}
}
- 測試
先啟動一下服務端,然后再啟動一下客戶端,我的login1()方法是有返回值的,當啟動了客戶端,就可以在服務端的執(zhí)行日志那里看到我的相關(guān)返回值啦
到了這里,關(guān)于java gradle 項目 在idea上 搭建一個簡單的thrift實例的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!