thrift使用(2):代码生成和接口调用

来源:互联网 发布:seo网络推广专员 编辑:程序博客网 时间:2024/06/01 07:20

1. 编写接口thrift

namespace java com.wzz.thrift.resultstruct Result   {    1: string result,    2: map<string,string> value  }  


namespace java com.wzz.thriftinclude "Result.thrift" service FuzaServ{   Result.Result helloWorld(1:string para)}

2. 使用thrift.exe生成代码,


thrift-0.10.0.exe -gen java FuzaServ.thrift

thrift-0.10.0.exe -gen java Result.thrift


3. 看到已经生成了代码,在文件夹下

将代码复制到eclipse中,开始写实现类
public class FuzaServImpl implements Iface{@Overridepublic Result helloWorld(String para) throws TException {System.out.println(para);Result r = new Result();return r;}}

4. 发布服务,编写服务端的代码
public class Server {public static void main(String[] args) throws TTransportException {TServerSocket serverTransport = new TServerSocket(7911);//设置服务器端口        Factory proFactory = new TBinaryProtocol.Factory();//设置协议工厂        TProcessor processor = new FuzaServ.Processor<FuzaServ.Iface>(new FuzaServImpl());//关联处理器与Hello.thrift文件中定义的服务的实现        TServer.Args tArgs = new TServer.Args(serverTransport);        tArgs.processor(processor);        tArgs.protocolFactory(proFactory);                TServer server = new TSimpleServer(tArgs);        System.out.println("Start server on port 7911");        server.serve();}}

5. 接口调用

public class Client {public static void main(String[] args) throws TException {TTransport transport = new TSocket("localhost", 7911);// 建立连接transport.open();TProtocol protocol = new TBinaryProtocol(transport);FuzaServ.Client client = new FuzaServ.Client(protocol);// 生成客户端实例对象Result helloWorld = client.helloWorld("hello");}}

另附:

pom文件,引入包
<dependency><groupId>org.apache.thrift</groupId><artifactId>libthrift</artifactId><version>0.10.0</version></dependency>





0 0
原创粉丝点击