Thrift入门
从官网介绍看应该是个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:int n1, 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); } }
Please call me JiangYouDang!