1、编写idl文件
helloService.thrift
namespace java com.bjcaijing.thrift.service
service HelloService {
string sayString(1:string param)
}
2、生成java文件
thrift-0.9.2.exe -gen java ..\src\main\resources\thrift\*
3、编写服务端
关键在这里Processor processor = new HelloService.Processor(new HelloServiceImpl());
package com.bjcaijing.thrift;
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.transport.TServerSocket;
import com.bjcaijing.thrift.service.HelloService;
import com.bjcaijing.thrift.service.HelloService.Processor;
import com.bjcaijing.thrift.service.impl.HelloServiceImpl;
public class Server {
public static void main(String[] args) throws Exception {
// 设置服务器端口
TServerSocket serverTransport = new TServerSocket(9090);
// 设置二进制协议工厂
Factory protocolFactory = new TBinaryProtocol.Factory();
// 处理器关联业务实现
Processor processor = new HelloService.Processor(
new HelloServiceImpl());
// 1. 使用单线程标准阻塞I/O模型
// TServer.Args simpleArgs = new TServer.Args(serverTransport);
//
// simpleArgs.processor(processor);
//
// simpleArgs.protocolFactory(protocolFactory);
//
// TServer server = new TSimpleServer(simpleArgs);
// server.serve();
// 2. 使用线程池服务模型
TThreadPoolServer.Args poolArgs = new TThreadPoolServer.Args(serverTransport);
poolArgs.processor(processor);
poolArgs.protocolFactory(protocolFactory);
TServer poolServer = new TThreadPoolServer(poolArgs);
System.out.println("开启thrift服务器,监听端口:9090");
poolServer.serve();
}
}
4、编写客户端调用
关键在:System.out.println(client.sayString("Hello world"));
package com.bjcaijing.thrift;
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 com.bjcaijing.thrift.service.HelloService;
public class Client {
public static void main(String[] args) throws Exception {
// 设置调用的服务地址-端口
TTransport transport = new TSocket("localhost", 9090);
// 使用二进制协议
TProtocol protocol = new TBinaryProtocol(transport);
// 使用的接口
HelloService.Client client = new HelloService.Client(protocol);
// 打开socket
transport.open();
System.out.println(client.sayString("Hello world"));
transport.close();
}
}
package com.bjcaijing.thrift.service.impl;
import org.apache.thrift.TException;
public class HelloServiceImpl implements com.bjcaijing.thrift.service.HelloService.Iface {
@Override
public String sayString(String param) throws TException {
return "thrift server say:" + param;
}
}
5、结果展示