以上是传输相同的内容时内容大小的对比。
以上是运行开销比较结果。
TCompactProtocol和TBinaryProtocol是Thrift支持的两种协议,其中TCompactProtocol使用Variable-Length Quantity (VLQ) 编码对数据进行压缩。
详细可以查看:http://www.javabloger.com/article/apache-thrift-architecture.html
接下来,我想讲述一下如何使用Thrift搭建C#版的客户端以及服务端通讯的程序。
1. 先从官网下载Thrift安装包以及签出SVN源码:
官网下载地址:http://thrift.apache.org/download/
这里我下载了一个Thrift compiler for Windows版本的EXE文件(thrift-0.7.0.exe)
签出SVN源码地址:http://svn.apache.org/repos/asf/thrift/trunk
2. 这里我利用文章(http://www.javabloger.com/article/thrift-java-code-example.html)的例子(该例子生成Java源码的),完成一个C#版本的示例。
3. 首先创建脚本,命名为textCsharp.thrift,脚本内容如下:
namespace java com.javabloger.gen.code # 注释1 struct Blog { # 注释2 1: string topic 2: binary content 3: i64 createdTime 4: string id 5: string ipAddress 6: map
4. 执行thrift命令:thrift -gen csharp testCsharp.thrift,这里说明一下:参数"csharp”意味着这里将自动生成C#代码,如果这里写java,python等等,可以用"java"或者"py”代替。
于是得到gen-csharp的目录,这个目录里面就包含支持Thrift的Blog以及ThriftCase的源代码,具体里面都生成什么代码,后面会做出介绍。
5. 然后,我现在打开SVN源码中的 trunk\lib\csharp\ 路径,我用项目打开
编译后,得到Thrift.dll文件,为了后面使用Thrift做准备。
6.新建工程,添加Server以及Client项目,把刚才生成的代码文件放入Common项目中。让Client和Server项目引用Thrift.dll类库。
7. 编写服务端程序:
public class Server { public void Start() { TServerSocket serverTransport = new TServerSocket(7911, 0, false); ThriftCase.Processor processor = new ThriftCase.Processor(new BusinessImpl()); TServer server = new TSimpleServer(processor, serverTransport); Console.WriteLine("Starting server _disibledevent=>"); server.Serve(); } }
其中BusinessImpl具体提供业务逻辑的实现:
public class BusinessImpl : ThriftCase.Iface { public int testCase1(int num1, int num2, String num3) { int i = num1 + num2; Console.Write( "testCase1 num1+num2 is :"+ i); Console.WriteLine( " num3 is :"+ num3); return i; } public List
让它继承ThriftCase.Iface接口。
8. 编写客户端程序:
class Client { static Dictionary
9. 运行Server以及Client:
从客户端调用的方法,服务端已经接收到了数据。
源代码下载:ThriftCSharp.rar
后面的文章,我会具体介绍下Thrift的工作机制和原理。
最新评论