Thrift
thrift是一个RPC(Remote Procedure Call)框架。其使用是通过编写IDL(Interface Definition Language)来同一规约服务端和客户端。这个IDL为.thrift文件。
实操记录
本文全程在windows下操作
首先下载thrift,这边下载的是0.13.0版本。
下载地址:http://archive.apache.org/dist/thrift/0.13.0/thrift-0.13.0.exe
(版本很重要,各个语言的thrift包都需要保持版本一致。)
编写IDL:
namespace netstd CloudAlbum.RPC.Interance
service AlbumS3{
bool Test(1:string str)
}
然后先生成客户端的代码:
thrift-0.13.0.exe --gen netstd AlbumS3.thrift
根据IDL中指定的namespace,代码会生成在".\gen-netstd\CloudAlbum\RPC\Interance"这个目录下。
将这个代码复制到准备好的.netcore类库项目目录下。
unget包需要下载ApacheThrift的0.13.0.1版本。类库项目和下面的控制台项目都需要下载。
控制台项目代码:
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using CloudAlbum.RPC.Interance;
using Thrift.Protocol;
using Thrift;
using Thrift.Transport;
using Thrift.Transport.Client;
namespace core_demo
{
class Program
{
static void Main(string[] args)
{
try
{
var transport = new TSocketTransport("127.0.0.1", 8080);
var protocol = new TBinaryProtocol(transport);
var client = new AlbumS3.Client(protocol);
Console.WriteLine("begin");
var task = client.TestAsync("hello");
task.Wait();
Console.WriteLine("end");
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
Console.Read();
}
}
}
这里有个小问题就是127.0.0.1这个ip需要换成电脑本身的ip。需要通过ipconfig查询。
生成服务端代码:
thrift-0.13.0.exe --gen py AlbumS3.thrift
生成代码在“.\gen-py”目录下,将这个代码复制到我们准备好的python目录中。
编写服务端程序Server.py
需要安装thrift包:
pip install thrift==0.13.0
from AlbumS3 import AlbumS3
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
class AlbumS3Handler:
def Test(self, str):
print str
return True
if __name__ == "__main__":
headler = AlbumS3Handler()
processor = AlbumS3.Processor(headler)
transport = TSocket.TServerSocket("0.0.0.0", 8080)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolAcceleratedFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print "begin"
server.serve()
然后先运行一下这个服务端:
python Server.py
在运行客户端控制台
可以成功看到
begin
hello