【thrift】 thrift入门
thrift 是Facebook开源的跨语言的RPC通信框架,支持的语言比较多,如java、c++、Python等
thrift提供的跨语言的编译工具,可以基于thrift idl语言编译出所支持语言的源代码文件
利用thrift,可以方便的开发出服务间的RPC通信框架,促进服务间的解耦
第一部分:thrift 入门
1.idl 文件,下面的说明均基于java语言:
namespace java com.ming.thrift.demo
service HelloService{
string helloWorld(1:string hello);
}
比较简单,就定义了一个Service和一个接口
比如生成java代码,则执行 thrift --gen java demo.thrift
2.实现Service接口
编译thrift idl生成的java代码是为 HelloService.java
里面包含了一个 Iface 的 interface
我们只需要实现这个 iface 接口即可,这里只有 helloWorld 这个方法
public class HelloServiceImpl implements HelloService.Iface {
public String helloWorld (String
hello) throws TException {
System. out.println( "hello
world "+hello);
return "I'm
server, hello";
}
}
3.编写server端
public class HelloServer
{
public static void main(String[]
args) throws TTransportException {
/*
* thrift 封装的 socket 层,使用端口7911构建一个非阻塞的socket
*/
TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(7911);
/*
* thrift 协议层,这里使用的是 二进制协议
*/
Factory proFactory = new TBinaryProtocol.Factory();
/*
* thrift idl接口的实现类
*/
HelloServiceImpl testimpl = new HelloServiceImpl();
/*
* thrift Processor 业务逻辑处理层
*/
TProcessor processor = new HelloService.Processor<HelloServiceImpl>(testimpl);
Args rpcArgs = new Args(serverTransport);
rpcArgs.processor(processor);
rpcArgs.protocolFactory(proFactory);
/*
* thrift server
*/
TServer server = new THsHaServer(rpcArgs);
System. out.println( "server
begin...");
server.serve();
}
}
thrift 服务端包含4个部分
transport层:经过封装的socket层
protocol层:网络读写的协议层,主要考虑的是数据的编解码与序列化反序列化等,为Processor提供输入输出流对象
Processor层:Processor封装了从输入流读数据及写数据到输出流的能力
server层:相当于一个组装员,把transport、protocol、Processor三者组装起来称为一个整体,对外提供服务
同时,其自身包含了服务端的业务处理框架,如线程池模型等
4.编写client端
public class HelloClient
{
public static void main(String[]
args) throws TException, InterruptedException
{
/*
* 构建socket
*/
TTransport transport = new TFramedTransport( new TSocket("localhost",
7911));
/*
* 链接到server
*/
transport.open();
/*
* 创建读写协议对象
*/
TProtocol protocol = new TBinaryProtocol(transport);
/*
* 这里的client 为thrift 编译生成的代码 HelloService 里client类
*/
Client client = new Client(protocol);
/*
* 调用 方法 helloWorld 整个 RPC调用过程由thrift处理,feel so easy
*/
String res = client.helloWorld( "I'm client");
System. out.println(res);
}
}
client的编写也比较简单,与传统的 socket 通信代码的编写没有太多的差异
thrift基本上把通信的细节已经封装好
不管是server还是client ,要进行网络通信,依然还是创建连接,从输入流读数据,写数据到输出流
通信的原理及流程都是一致的