Thrift是什么?
是Facebook开源的跨语言RPC框架。
实战
这里实现一个简单的服务CalculatorService。引入maven依赖
org.apache.thrift
libthrift
0.9.2
编写Thrift接口定义文件
Thrift接口定义(IDL)文件采用抽象注解的方式说明类型信息,用于告知thrift代码生成器如何生成相应语言的接口或者方法声明。
namespace java com.vonzhou.learn.rpc
service CalculatorService {
/*** A method definition looks like C code. It has a return type, arguments,* and optionally a list of exceptions that it may throw. Note that argument* lists and exception lists are specified using the exact same syntax as* field lists in struct or exception definitions.*/
void ping(),
i32 add(1:i32 num1, 2:i32 num2),
}使用Thrift compiler根据IDL文件生成对应的源文件
这里仅仅配置了Java命名空间,运行上述命令后会生成CalculatorService.java文件。实现服务接口CalculatorService.Iface
public class CalculatorServiceHandler implements CalculatorService.Iface{
public void ping() throws TException {
System.out.println("ping");
}
public int add(int num1, int num2) throws TException {
return num1 + num2;
}
}实现Thrift Server
public class ThriftServer {
public static void start(CalculatorService.Processor processor) {
try {
/*** 服务器端传输层初始化*/
TServerTransport serverTransport = new TServerSocket(9090);
/*** Thrift Server 这里采用简单单线程实现, 用于测试环境*/
TServer server = new TSimpleServer(new TServer.Args(serverTransport).processor(processor));
System.out.println("Starting the simple thrift server...");
/*** 启动服务*/
server.serve();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
start(new CalculatorService.Processor(new CalculatorServiceHandler()));
}
}实现Thrift Client
public class ThriftClient {
public static void main(String[] args) {
try {
TTransport transport = new TSocket("localhost", 9090);
/*** Opens the transport for reading/writing.*/
transport.open();
/*** 指定具体的 protocol*/
TProtocol protocol = new TBinaryProtocol(transport);
/*** TServiceClient :通过 protocol 和 transport 与具体的服务通信,理解为 Stub*/
CalculatorService.Client client = new CalculatorService.Client(protocol);
/*** RPC call*/
System.out.println(client.add(100, 200));
transport.close();
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException x) {
x.printStackTrace();
}
}
}
理解
TTransport:IO层的封装抽象,打开关闭,读写传输层,TTransport具体对应有不同的实现:
TServerTransport:服务器端IO层抽象,用于listen, accept连接请求。
TSocket:是TTransport基于socket的实现,同样的,TServerSocket是TServerTransport 基于socket的实现, 是Thrift中对ServerSocket的包装。
TProtocol:表示RPC通信的消息传输格式,实现有二进制(TBinaryProtocol),JSON(TJSONProtocol)格式等。
参考