最近在hive新增Thirft接口,于是學(xué)習(xí)了一下Thirft的使用
org.apache.thrift libthrift 0.12.0
在resource下創(chuàng)建一個hello.thrift文件
namespace java service.demo
service service.demo.HelloWorld{string sayHello(1: string param)
}
進入resource,thrift -r -gen java hello.thrift
會在當前路徑創(chuàng)建出一個gen-java.service.demo的文件夾。文件夾下面有Hello.java文件,將其移動到main目錄的service.demo包中
package service.demo;
import org.apache.thrift.TException;
public class HelloWorldIfaceImpl implements HelloWorld.Iface {public String sayHello(String param) throws TException {return "hello! "+ param;
}
}
package service.demo;
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;
public class HelloWorldServer {public static void main(String[] args) {try {System.out.println("Server Starting....");
// TServer的參數(shù),并添加需要的處理過程和協(xié)議
TServer.Args tArgs = new TServer.Args(new TServerSocket(666));
// 1.過程
TProcessor tprocessor = new HelloWorld.Processor(new HelloWorldIfaceImpl()); // 構(gòu)造server的處理過程
tArgs.processor(tprocessor);
// 2.協(xié)議
tArgs.protocolFactory(new TBinaryProtocol.Factory()); // 選用Protocol協(xié)議
// 構(gòu)建server并啟動
TServer server = new TSimpleServer(tArgs);
server.serve();
}catch (TTransportException e) {e.printStackTrace();
}
}
}
啟動后,開源看到日志輸出
3. 創(chuàng)建客戶端并訪問服務(wù)端
package service.demo;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
public class HelloWorldClient {public static void main(String[] args) {System.out.println("Client starting....");
TTransport transport = null;
try {// 綁定通信端口
transport = new TSocket("localhost", 666, 30000);
transport.open();
// 構(gòu)建協(xié)議,注意和服務(wù)端一致
TProtocol protocol = new TBinaryProtocol(transport);
// 創(chuàng)建客戶端
HelloWorld.Client client = new HelloWorld.Client(protocol);
// 客戶端請求服務(wù)端,獲得結(jié)果并輸出
String result = client.sayHello("Spider-Man");
System.out.println(result);
} catch (TTransportException e) {e.printStackTrace();
} catch (TException e) {e.printStackTrace();
} finally {if (null != transport) {transport.close();
}
}
}
}
運行后成功拿到結(jié)果
負責(zé)連接調(diào)度、服務(wù)的生命周期,定義接口是TServer
處理請求,具體的實現(xiàn)由生成的代碼處理,定義接口是 TProcessor
請求協(xié)議,數(shù)據(jù)的編解碼實現(xiàn),定義接口是 TProtocol
底層的連接,提供了讀寫的抽象實現(xiàn);服務(wù)端定義是 TServerTransport
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧