Thrift 使用
Thrift 是apache开源的rpc框架,支持多种语言绑定。相对protobuf,提供server,序列化等一站式解决方案。
一. 下载
http://thrift.apache.org/download
二. 编写IDL
namespace java org.sun.service service SimpleThriftService { string getStr( 1:string src, 2:string dst ); i32 getInt( 1:i32 val ); map<i32,i32> getMap( 1:string name ); }
该IDL是用于生成各语言绑定的描述文件,pb中对应*.proto文件。thrift的IDL支持数据类型比较丰富,包含struct/map。
Thrift Types:
Base Types:
bool: A boolean value (true or false)
byte: An 8-bit signed integer
i16: A 16-bit signed integer
i32: A 32-bit signed integer
i64: A 64-bit signed integer
double: A 64-bit floating point number
string: A text string encoded using UTF-8 encoding
Structs
Containers:
list, set, map
三. 生成Java Binding
thrift --gen java test_service.thrift
当前目录生成:./gen-java/org/sun/service/SimpleThriftService.java
四. 编写实现类
// 实现Binding class的Iface接口 public class ThriftServiceImpl implements SimpleThriftService.Iface { public String getStr(String src, String dst) throws TException { System.out.println( "Input: " + src + "\t" + dst ); String strResult = String.format( "%s-%s", src, dst ); return strResult; } public int getInt(int val) throws TException { int sum = 10*val; return sum; } public Map<Integer, Integer> getMap(String name) throws TException { System.out.println( "Name: " + name ); Map<Integer,Integer> pMap = new HashMap<Integer,Integer>(); pMap.put( 1, 1 ); return pMap; } }
五. 启动server
Thrift对外提供工作模式:TSimpleServer、TNonblockingServer、TThreadPoolServer、TThreadedSelectorServer等。
Thrift支持通信协议格式:TCompactProtocol、TBinaryProtocol、TJSONProtocol等。
/** * Thrift Server */ private static void main( String[] args) throws TTransportException { ThriftServiceImpl m_ServImpl = new ThriftServiceImpl(); // 实现类 TProcessor tProcessor = new SimpleThriftService.Processor<SimpleThriftService.Iface>( m_ServImpl ); TNonblockingServerSocket nioSocket = new TNonblockingServerSocket( 12345 ); // 设置参数 TNonblockingServer.Args tnbArgs = new TNonblockingServer.Args(nioSocket); tnbArgs.processor(tProcessor); // 设置处理器 tnbArgs.transportFactory(new TFramedTransport.Factory()); // 按块方式传输 tnbArgs.protocolFactory(new TBinaryProtocol.Factory()); // 二进制序列化协议 // 启动TCP服务 m_Server = new TNonblockingServer( tnbArgs ); // 循环提供服务 m_Server.serve(); }
六. Client测试
/** * Thrift Client */ public static void main(String[] args) { // 建立tcp client TTransport m_Socket = new TFramedTransport( new TSocket( "127.0.0.1", 12345, 2000 ) ); // 设置二进制协议 TProtocol protocol = new TBinaryProtocol( m_Socket ); SimpleThriftService.Client client = new SimpleThriftService.Client(protocol); try { m_Socket.open(); // 调用远程函数 String result = client.getStr( "hello", "world" ); System.out.println( "Result: " + result ); m_Socket.close(); } catch (TException e) { e.printStackTrace(); } }
七. 抓包分析
Wireshark居然能识别thrift协议,thrift协议包括header(18字节) + Data,很明显thrift未对字段做压缩,相对于pb比较占用网络带宽。
参考文章
上一篇: 类型信息解读 java类型信息反射
下一篇: thrift servlet
推荐阅读