thrift 简介三
2017-12-11 本文已影响0人
sunny4handsome
thrift 使用
之前我们看了一些thrift的概念,现在我们通过hello world来学习thrift的使用。
thrift idl
service HelloWorldService{
string sayHello(1:string username)
}
通过thrift生成对应的代码
thrift 安装
- mac下安装(前提安装homebrew)
brew install thrift - window 可以在官网下载
https://thrift.apache.org/download
thrift 生成代码
thrift -r -gen java hello.thrift
code
pom文件
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.10.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.0</version>
</dependency>
</dependencies>
实现
public class HelloWorldImpl implements HelloWorldService.Iface{
@Override
public String sayHello(String username) throws TException {
return "hi, "+ username;
}
}
server
public class AppServer {
public static void main(String[] args) {
AppServer appServer = new AppServer();
appServer.startServer();
}
public void startServer(){
TProcessor tProcessor = new HelloWorldService.Processor<HelloWorldImpl>(new HelloWorldImpl());
try {
TServerSocket serverSocket = new TServerSocket(8090);
TServer.Args tArgs = new TServer.Args(serverSocket);
tArgs.processor(tProcessor);
tArgs.protocolFactory(new TBinaryProtocol.Factory());
TServer server = new TSimpleServer(tArgs);
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
}
}
client
public class AppClient {
public static final String SERVER_IP = "localhost";
public static final int SERVER_PORT = 8090;
public static final int TIMEOUT = 30000;
public void startClient(String username){
TTransport transport = null;
transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
TProtocol protocol = new TBinaryProtocol(transport);
HelloWorldService.Client client = new HelloWorldService.Client(protocol);
try {
transport.open();
String result = client.sayHello(username);
System.out.println("get server result = " + result);
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
AppClient appClient = new AppClient();
appClient.startClient("payne");
}
}
上面的是简单的单线程服务模型,一般用于测试。
除此之外还有模型如下:根据实际选用:
- TThreadPoolServer 服务模型
线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。 - TNonblockingServer 服务模型
使用非阻塞式IO,服务端和客户端需要指定 TFramedTransport 数据传输的方式。 - THsHaServer服务模型
半同步半异步的服务端模型,需要指定为: TFramedTransport 数据传输的方式。 - 异步客户端