Thrift入門
阿新 • • 發佈:2017-10-08
tid 客戶端 監聽 prot stat sys div tac exc
從官網介紹看應該是個RPC框架,通過thrift定義接口,根據thrift文件生成各種語言的代碼,c++, python, java....這裏工作主要用到java。從晚上抄了個乘法的例子
1. pom依賴
<dependency> <groupId>org.apache.thrift</groupId> <artifactId>libthrift</artifactId> <version>0.10.0</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.13</version> </dependency>
這裏加了個logback日誌,方便查看框架日誌輸出
2. 定義接口
multiple.thrift
namespace java tutorial namespace py tutorial /* C like comments are supported */ // This is also a valid comment typedef i32 int // We can use typedef to get pretty names for the types we are using service MultiplicationService { int multiply(1:intn1, 2:int n2), }
這裏定義了一個乘法接口,接收兩個整形參數,返回他們的乘積
3. 使用thrift編譯器生成java代碼
thrift --gen java multiple.thrift
4. 服務端代碼
MultiplicationHandler.java
/** * Created by GuanXF on 2017/10/8. */ public class MultiplicationHandler implements MultiplicationService.Iface { public int multiply(int n1, int n2) throws TException { System.out.println("n1 = " + n1 + ", n2 = " + n2); return n1 * n2; } }
MultiplicationServer.java
/**
* Created by GuanXF on 2017/10/8.
*/
public class MultiplicationServer {
public static MultiplicationHandler handler;
public static MultiplicationService.Processor processor;
public static void main(String[] args) {
handler = new MultiplicationHandler();
processor = new MultiplicationService.Processor(handler);
final Runnable simple = new Runnable() {
public void run() {
simple(processor);
}
};
new Thread(simple).start();
} //main
public static void simple(MultiplicationService.Processor processor){
try{
TServerTransport serverTransport = new TServerSocket(9090);
TServer server = new TSimpleServer(new TServer.Args(serverTransport).processor(processor));
System.out.println("Starting the simple server...");
server.serve();
}catch (Exception e){
e.printStackTrace();
}
}
}
這裏,服務端,應該是使用socket監聽9090端口。
5.客戶端代碼
MultiplicationClient.java
/** * Created by GuanXF on 2017/10/8. */ public class MultiplicationClient { public static void main(String[] args) { try{ TTransport transport; transport = new TSocket("localhost", 9090); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); MultiplicationService.Client client = new MultiplicationService.Client(protocol); perform(client); transport.close(); }catch (Exception e){ e.printStackTrace(); } } //main private static void perform(MultiplicationService.Client client) throws TException { int product = client.multiply(3, 5); System.out.println("3 * 5 = " + product); } }
Thrift入門