Thrift安装与环境配置
安装
下载
下载地址:http://archive.apache.org/dist/thrift/0.10.0/
将thrift-0.10.0.exe放置于指定目录,例如F:\thrift,并将其重命名为thrift.exe。若未进行重命名操作,后续执行命令时需使用完整文件名thrift-0.10.0作为指令前缀。
配置环境变量
向Path中添加新的变量值,该值应指向包含thrift.exe的目录路径,例如thrift.exe所在的F:\thrift。
测试
在命令行窗口中输入thrift -version,若终端正确返回thrift的版本信息,则说明环境配置成功且工具可用。
使用
编写IDL接口
HelloService.thrift
namespace java com.thrift.demo.service
service HelloService{
string sayHello(1:string username)
}
编译
执行编译命令后,系统将自动生成对应的HelloService相关代码文件。
thrift -gen java HelloService.thrift
编写实现类
HelloServiceImpl.java
public class HelloServiceImpl implements HelloService.Iface {
@Override
public String sayHello(String username) throws TException {
return "Hello Thrift Service : " + username;
}
}
编写服务端代码
public class HelloServer {
public static final int SERVER_PORT = 8090;
public void startServer() {
try {
System.out.println("HelloService TSimpleServer start ....");
TProcessor tprocessor = new HelloService.Processor(new HelloServiceImpl());
// 简单的单线程服务模型,一般用于测试
TServerSocket serverTransport = new TServerSocket(SERVER_PORT);
TServer.Args tArgs = new TServer.Args(serverTransport);
tArgs.processor(tprocessor);
tArgs.protocolFactory(new TBinaryProtocol.Factory());
TServer server = new TSimpleServer(tArgs);
server.serve();
} catch (Exception e) {
System.out.println("Server start error!!!");
e.printStackTrace();
}
}
public static void main(String[] args) {
HelloServer server = new HelloServer();
server.startServer();
}
}
编写客户端代码
public class HelloClient {
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;
try {
transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
// 协议要和服务端一致
TProtocol protocol = new TBinaryProtocol(transport);
HelloService.Client client = new HelloService.Client(protocol);
transport.open();
String result = client.sayHello(userName);
System.out.println("Thrify client result =: " + result);
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
} finally {
if (null != transport) {
transport.close();
}
}
}
public static void main(String[] args) {
HelloClient client = new HelloClient();
client.startClient("Michael");
}
}
运行
启动顺序上,需先运行服务端程序,待其就绪后再启动客户端程序进行交互。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对本站的支持。如果你想了解更多相关内容请查看下面相关链接