Thrift 多线程阻塞式IO服务模型
import com.service.demo.Hello;
import com.service.demo.impl.HelloServiceImpl;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;
/**
* Thrift 多线程阻塞式IO服务模型-TThreadPoolServer
*/
public class HelloServiceServer {
/**
* 启动 Thrift 服务器
* @param args
*/
public static void main(String[] args) {
try {
// 设置服务端口为 7911 // 阻塞IO
TServerSocket serverTransport = new TServerSocket(7911);
// 设置协议工厂为 TBinaryProtocol.Factory
// 关联处理器与 Hello 服务的实现
TProcessor processor = new Hello.Processor(new HelloServiceImpl());
//设置传输格式工厂为TBinaryProtocol(二进制格式).
TBinaryProtocol.Factory proFactory=new TBinaryProtocol.Factory();
//线程池服务模型参数,使用标准的阻塞式IO,预先创建一组线程处理请求。//多线程服务模型
TThreadPoolServer.Args args1=new TThreadPoolServer.Args(serverTransport);
args1.processor(processor);
//客户端协议要一致
args1.protocolFactory(proFactory);
//线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。
TServer server =new TThreadPoolServer(args1);
System.out.println("Start server on port 7911...");
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
}
}
2、 客户端
package com.thriftClient;
import com.service.demo.Hello;
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 HelloServiceClient {
/**
* 调用 Hello 服务
* @param args
*/
public static void main(String[] args) {
try {
// 设置调用的服务地址为本地,端口为 7911 // 设置传输通道
TTransport transport = new TSocket("localhost", 7911);
transport.open();
// 设置传输协议为 TBinaryProtocol
TProtocol protocol = new TBinaryProtocol(transport);
Hello.Client client = new Hello.Client(protocol);
// 调用服务的 helloString 方法
client.helloVoid();
String str = client.helloString("Thrift测试");
System.out.println(str);
transport.close();
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
}
}
}
参考资料:
http://blog.youkuaiyun.com/column/details/slimina-thrift.html