1. 编写接口thrift
namespace java com.wzz.thrift.result
struct Result
{
1: string result,
2: map<string,string> value
}
namespace java com.wzz.thrift
include "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{
@Override
public Result helloWorld(String para) throws TException {
System.out.println(para);
Result r = new Result();
return r;
}
}
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>