Thrift下Java客戶端與伺服器端的開發
阿新 • • 發佈:2019-01-27
1建立Thrift檔案
Thrift檔案與程式語言無關,用於定義資料型別和服務介面,然後生成用來構建RPC客戶和伺服器所需的全部程式碼。
1.1編寫testJava.thrift
[html] view plain copy print?- #!/usr/local/bin/thrift --gen java
- namespace java Test
- service Something {
- i32 ping()
- }
1.2執行thrift編譯器,生成專案原始檔
在linux命令列下輸入:Thrift –gen javatestJava.thrift
生成的原始檔在./gen-java/目錄下。
2建立Java伺服器
進入./gen-java目錄,確保系統的CLASSPATH設定正確。libthrift.jar,,slf4j-api和slf4j-simple這幾個包都需要包含在CLASSPATH裡。
2.1編寫SomethingImpl.java
[html] view plain copy print?- package Test;
- import org.apache.thrift.TException;
- class SomethingImpl implements Something.Iface {
-
public SomethingImpl() {}
- public int ping() throws TException {
- System.out.println( "Recieve ping from client..." );
- return 0;
- }
- }
2.2建立Server.java
[html] view plain copy print?- package Test;
- import java.io.IOException;
- import org.apache.thrift.protocol.TBinaryProtocol;
-
import org.apache.thrift.protocol.TBinaryProtocol.Factory;
- import org.apache.thrift.server.TServer;
- import org.apache.thrift.server.TThreadPoolServer;
- import org.apache.thrift.transport.TServerSocket;
- import org.apache.thrift.transport.TTransportException;
- public class Server {
- private void start() {
- try {
- TServerSocket serverTransport = new TServerSocket(7911);
- Something.Processor processor = new Something.Processor(newSomethingImpl());
- Factory protFactory = new TBinaryProtocol.Factory(true, true);
- TServer server = new TThreadPoolServer(processor, serverTransport,protFactory);
- System.out.println("Starting server on port 7911 ...");
- server.serve();
- } catch (TTransportException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static void main(String args[]){
- Server srv = new Server();
- srv.start();
- }
- }
3建立Java客戶端
建立Client.java
[html] view plain copy print?- package Test;
- import java.io.IOException;
- import org.apache.thrift.*;
- import org.apache.thrift.protocol.*;
- import org.apache.thrift.transport.*;
- public class Client {
- public static void main(String [] args) {
- try {
- TTransport transport = new TSocket("localhost", 7911);
- TProtocol protocol = new TBinaryProtocol(transport);
- Something.Client client =new Something.Client(protocol);
- transport.open();
- System.out.println("Client calls ping()");
- client.ping();
- transport.close();
- } catch (TException x) {
- x.printStackTrace();
- }
- }
- }
4編譯及執行
4.1編譯
在linux命令列下輸入:javac *.java,生成客戶端與伺服器端的class檔案。
4.2執行
首先啟動伺服器。退到gen-java目錄,輸入java Test/Server,螢幕顯示如下:
Starting server on port 7911 ...
然後啟動客戶端。在同一目錄下輸入java Test/Client,螢幕顯示如下:
Client calls ping()
這時伺服器端的輸出多了一行:
Recieve ping from client...