看到一篇介绍thrift 最基本应用的 几句话就可以说清楚怎么使用 记录下
简单的实现一个PING的功能
1.安装thrift
http://thrift.apache.org/download/
人人网镜像下载:
http://labs.renren.com/apache-mirror/thrift/0.6.1/thrift-0.6.1.exe
2.编写Thrift文件(定义接口,结构,异常等),保存为test.thrift
namespace java net.johnc.thriftservice Test{
void ping(1: i32 length)
}
3.生成接口代码
把thrift-0.6.1.exe和test.thrift文件放在同一个目录,当然也可以把thrift-0.6.1.exe文件放进环境变量
进入DOS命令执行:thrift-0.6.1.exe --gen java test.thrift
生成文件 gen-java/net/johnc/thrift/Test.java
4.编写服务端接口实现类
在POM.xml文件加入以下依赖:
<dependency>
<groupId>org.apache.thrift</groupId> <artifactId>libthrift</artifactId>
<version>0.6.1</version>
</dependency>
把生成的Test.java复制到项目下 并实现该接口
package net.johnc.thrift; 2 3 import org.apache.thrift.TException; 4 5 public class TestImpl implements Test.Iface { 6 7 public void ping(int length) throws TException { 8 System.out.println("calling ping ,length=" + length); 9 } 10 11 }
5.编写启动服务代码
package net.johnc.thrift; import net.johnc.thrift.Test.Processor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TBinaryProtocol.Factory; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.server.TThreadPoolServer.Args; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TTransportException; public class Server { public void startServer() { try { TServerSocket serverTransport = new TServerSocket(1234); Test.Processor process = new Processor(new TestImpl()); Factory portFactory = new TBinaryProtocol.Factory(true, true); Args args = new Args(serverTransport); args.processor(process); args.protocolFactory(portFactory); TServer server = new TThreadPoolServer(args); server.serve(); } catch (TTransportException e) { e.printStackTrace(); } } public static void main(String[] args) { Server server = new Server(); server.startServer(); } }
6.编写客户端代码
package net.johnc.thrift; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; public class Client { public void startClient() { TTransport transport; try { transport = new TSocket("localhost", 1234); TProtocol protocol = new TBinaryProtocol(transport); Test.Client client = new Test.Client(protocol); transport.open(); client.ping(2012); transport.close(); } catch (TTransportException e) { e.printStackTrace(); } catch (TException e) { e.printStackTrace(); } } public static void main(String[] args) { Client client = new Client(); client.startClient(); } }