一:thrift 框架引入java
上一篇文章咱們瞭解了基於java的rpc實現方式。很是的核心,可是也很是的簡單。代碼不夠通用,不支持異步等詳細的功能。若是須要的話,咱們得手動寫代碼去作封裝和功能的完善。咱們常說不要重複造輪子,有沒有現成的rpc框架能讓我直接用呢?確定有,並且不止一種。好比 Dubbo,gRPC,Thrift等。apache
二:thrift的使用框架
(1)下載 thrifteclipse
去官網(http://thrift.apache.org/download)下載 thrift-x.x.x.exe 文件異步
(2)配置環境變量(爲了在任意路徑都能使用thrift命令)socket
在path中加一下thrift-x.x.x.exe文件的路徑。好比我把這個文件放到了 C:\soft\developSoft\thrift-0.12.0 目錄下maven
(3)編寫Hello.thrift文件,聲明rpc方法和類名等信息ide
namespace java com.cs.thrift service Hello{ string helloString(1:string para) i32 helloInt(1:string para) bool helloBoolean(1:bool para) void helloVoid() string helloNull() }
(4)經過thrift生成對應的java類文件測試
(5)新建一個maven項目,把生成的類copy到myeclipse中(拷貝gen-java目錄下的全部文件便可)ui
(6)編寫服務的實現類
新建 HelloServiceImpl,實現 Hello.Iface。並實現裏面的方法。
public class HelloServiceImpl implements Hello.Iface{ @Override public String helloString(String para) throws TException { // TODO Auto-generated method stub return "這是個人一個thrift hello java——————" + para; } @Override public int helloInt(String para) throws TException { // TODO Auto-generated method stub return 0; } @Override public boolean helloBoolean(boolean para) throws TException { // TODO Auto-generated method stub return false; } @Override public void helloVoid() throws TException { // TODO Auto-generated method stub } @Override public String helloNull() throws TException { // TODO Auto-generated method stub return null; } }
(7)編寫server
import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TSimpleServer; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TTransportException; /** * 編寫 Thrift服務端,並啓動 * @author cuishuai01 */ public class HelloServiceServer { public static void main(String[] args) throws TTransportException { //設置服務監聽端口爲 8888 TServerSocket tServerSocket = new TServerSocket(8888); //建立本身具體的processor 並 關聯Hello服務的實現 TProcessor tProcessor = new Hello.Processor<Hello.Iface>(new HelloServiceImpl()); //關聯processor TServer.Args tArgs = new TServer.Args(tServerSocket); tArgs.processor(tProcessor); //設置協議工廠爲 TBinaryProtocol.Factory tArgs.protocolFactory(new TBinaryProtocol.Factory()); TServer tServer = new TSimpleServer(tArgs);
System.out.println("下面開始監聽客戶端發來的服務請求!"); tServer.serve(); } }
(8)編寫client
/** * 編寫客戶端,並啓動 * @author cuishuai01 */ public class HelloClient { public static void main(String[] args) throws Exception { //設置服務端的信息 TTransport tTransport = new TSocket("127.0.0.1", 8888, 3000); //協議要和服務端一致 TProtocol tProtocol = new TBinaryProtocol(tTransport); // TProtocol tProtocol = new TCompactProtocol(tTransport); // TProtocol tProtocol = new TJSONProtocol(tTransport); Hello.Client client = new Hello.Client(tProtocol); tTransport.open();//開啓socket String result = client.helloString("thrift java client");//客戶端調用服務端方法 System.out.println(result);//打印服務端方法的返回結果 } }
(9)測試
啓動 HelloServiceServer, 再執行 HelloClient 來調用服務端的方法,效果以下。