Thrift 非阻塞式IO服務模型
1、 服務端
package com.thriftServer;
import com.service.demo.Hello;
import com.service.demo.impl.HelloServiceImpl;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TTransportException;
/**
* Created by ssjk on 2016/10/21.
* Thrift 非阻塞式IO服務模型-TNonblockingServer
* 使用非阻塞式IO,服務端和客戶端需要指定 TFramedTransport 數據傳輸的方式。
*/
public class HelloServiceSercer02 {
public static void main(String[] args) {
try {
// 設置服務端口爲 7911 // 傳輸通道 - 非阻塞方式
TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(7911);
// 設置協議工廠爲 TBinaryProtocol.Factory
// 關聯處理器與 Hello 服務的實現
TProcessor tprocessor = new Hello.Processor(new HelloServiceImpl());
//異步IO,需要使用TFramedTransport,它將分塊緩存讀取。
TNonblockingServer.Args tArgs = new TNonblockingServer.Args(serverTransport);
tArgs.processor(tprocessor);
tArgs.transportFactory(new TFramedTransport.Factory());
//使用高密度二進制協議
tArgs.protocolFactory(new TCompactProtocol.Factory());
//線程池服務模型,使用標準的阻塞式IO,預先創建一組線程處理請求。
TServer server =new TNonblockingServer(tArgs);
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.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
public class HelloServiceClient02 {
/**
* 調用 Hello 服務
* @param args
*/
public static void main(String[] args) {
try {
//設置傳輸通道,對於非阻塞服務,需要使用TFramedTransport,它將數據分塊發送
TTransport transport = new TFramedTransport(new TSocket("localhost", 7911,3000));
transport.open();
// 協議要和服務端一致
//HelloTNonblockingServer
////使用高密度二進制協議
TProtocol protocol = new TCompactProtocol(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.csdn.net/zhu_tianwei/article/details/44002929