在Windows系统下安装Thrift的方法与使用讲解
安装
下载
下载地址:http://archive.apache.org/dist/thrift/0.10.0/
将thrift-0.10.0.exe放到一个文件下,如F:\thrift下,将其重命名为thrift.exe。如果不重命名,需要使用thrift-0.10.0调用thrift命令。
配置环境变量
向Path中添加变量值,值为thrift.exe的地址,如F:\thrift。
测试
命令行输入thrift-version,如果输出thrift的版本即表明安装成功。
使用
编写IDL接口
HelloService.thrift
namespacejavacom.thrift.demo.service
serviceHelloService{
stringsayHello(1:stringusername)
}
编译
编译之后会生成类HelloService。
thrift-genjavaHelloService.thrift
编写实现类
HelloServiceImpl.java
publicclassHelloServiceImplimplementsHelloService.Iface{
@Override
publicStringsayHello(Stringusername)throwsTException{
return"HelloThriftService:"+username;
}
}
编写服务端代码
publicclassHelloServer{
publicstaticfinalintSERVER_PORT=8090;
publicvoidstartServer(){
try{
System.out.println("HelloServiceTSimpleServerstart....");
TProcessortprocessor=newHelloService.Processor(newHelloServiceImpl());
//简单的单线程服务模型,一般用于测试
TServerSocketserverTransport=newTServerSocket(SERVER_PORT);
TServer.ArgstArgs=newTServer.Args(serverTransport);
tArgs.processor(tprocessor);
tArgs.protocolFactory(newTBinaryProtocol.Factory());
TServerserver=newTSimpleServer(tArgs);
server.serve();
}catch(Exceptione){
System.out.println("Serverstarterror!!!");
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
HelloServerserver=newHelloServer();
server.startServer();
}
}
编写客户端代码
publicclassHelloClient{
publicstaticfinalStringSERVER_IP="localhost";
publicstaticfinalintSERVER_PORT=8090;
publicstaticfinalintTIMEOUT=30000;
publicvoidstartClient(StringuserName){
TTransporttransport=null;
try{
transport=newTSocket(SERVER_IP,SERVER_PORT,TIMEOUT);
//协议要和服务端一致
TProtocolprotocol=newTBinaryProtocol(transport);
HelloService.Clientclient=newHelloService.Client(protocol);
transport.open();
Stringresult=client.sayHello(userName);
System.out.println("Thrifyclientresult=:"+result);
}catch(TTransportExceptione){
e.printStackTrace();
}catch(TExceptione){
e.printStackTrace();
}finally{
if(null!=transport){
transport.close();
}
}
}
publicstaticvoidmain(String[]args){
HelloClientclient=newHelloClient();
client.startClient("Michael");
}
}
运行
先运行服务端,再运行客户端。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接