最近在hive新增Thirft接口,于是学习了一下Thirft的使用
<dependency>
<groupId>org.apache.thriftgroupId>
<artifactId>libthriftartifactId>
<version>0.12.0version>
dependency>
在resource下创建一个hello.thrift文件
namespace java service.demo
service service.demo.HelloWorld{
string sayHello(1: string param)
}
进入resource,thrift -r -gen java hello.thrift
会在当前路径创建出一个gen-java.service.demo的文件夹。文件夹下面有Hello.java文件,将其移动到main目录的service.demo包中
package service.demo;
import org.apache.thrift.TException;
public class HelloWorldIfaceImpl implements HelloWorld.Iface {
public String sayHello(String param) throws TException {
return "hello! "+ param;
}
}
package service.demo;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;
public class HelloWorldServer {
public static void main(String[] args) {
try {
System.out.println("Server Starting....");
// TServer的参数,并添加需要的处理过程和协议
TServer.Args tArgs = new TServer.Args(new TServerSocket(666));
// 1.过程
TProcessor tprocessor = new HelloWorld.Processor<HelloWorld.Iface>(new HelloWorldIfaceImpl()); // 构造server的处理过程
tArgs.processor(tprocessor);
// 2.协议
tArgs.protocolFactory(new TBinaryProtocol.Factory()); // 选用Protocol协议
// 构建server并启动
TServer server = new TSimpleServer(tArgs);
server.serve();
}catch (TTransportException e) {
e.printStackTrace();
}
}
}
启动后,开源看到日志输出
3. 创建客户端并访问服务端
package service.demo;
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 HelloWorldClient {
public static void main(String[] args) {
System.out.println("Client starting....");
TTransport transport = null;
try {
// 绑定通信端口
transport = new TSocket("localhost", 666, 30000);
transport.open();
// 构建协议,注意和服务端一致
TProtocol protocol = new TBinaryProtocol(transport);
// 创建客户端
HelloWorld.Client client = new HelloWorld.Client(protocol);
// 客户端请求服务端,获得结果并输出
String result = client.sayHello("Spider-Man");
System.out.println(result);
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
} finally {
if (null != transport) {
transport.close();
}
}
}
}
运行后成功拿到结果
负责连接调度、服务的生命周期,定义接口是TServer
处理请求,具体的实现由生成的代码处理,定义接口是 TProcessor
请求协议,数据的编解码实现,定义接口是 TProtocol
底层的连接,提供了读写的抽象实现;服务端定义是 TServerTransport