Thrift 下载
去官网 https://thrift.apache.org/download 下载两个文件:
- thrift-0.9.3.exe
- thrift-0.9.3.tar.gz
前者用于将 .thrift 文件编译成其他语言文件(如 .cs, .cpp 等),后者是源代码,用于生成不同语言的 thrift 库文件。
下载完成后:
- 将 thrift-0.9.3.exe 文件重命名为 thrift.exe 并存储在 C 盘新建的文件夹Thrift 下,将 C:/Thrift 加入环境变量,重启电脑使配置生效
- 将 thrift-0.9.3.tar.gz 解压,进入 lib/csharp/src 文件夹,使用 Visual Studio 打开 Thrift.sln 文件,编译。完成后可在 bin/Debug 中找到 Thrift.dll 文件,就是我们每次使用 Thrift 必须加载的库文件。(提示:编译时可能会弹框提示需要 .net framework 3.5 的库,按照提示链接去官网 https://www.microsoft.com/en-us/download/details.aspx?id=22 下载安装即可)
编写 Thrift 脚本
假设服务端(Server)为客户端(Client)提供简单的数学运算功能。编写 demo.thrift 脚本如下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
从控制台进入 demo.thrift 的目录后,编译该文件为 C# 代码:
- 1
- 1
随后会生成一个 gen-csharp 的文件夹,其中包括 MathService.cs 文件,该文件需要同时导入到 Server 和 Client 的程序中,下面将详细说明。
如果是两种语言,如 Java 和 C# 通信的话,需要 –gen csharp 和 –gen java 分别编译一次,将得到的 .cs 和 .class 文件分别导入到两个项目中。
Server 程序
在 Visual Studio 中新建 C# Console Application 程序:ThriftServer。将 Thrift.dll. 导入到 Reference 中,同时将之前生成的 MathService.cs 导入项目中,并在 Program.cs 中包含:
- 1
- 2
- 1
- 2
新建一个类 MathServer.cs (注意不是 MathService.cs),实现 MathService.Iface 接口:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
然后修改 Program.cs 中的 Main 函数为:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
这样 ThriftServer 项目就可以运行了。它开启 9095 端口(可以自设),然后等待 Client 与其通信。
Client 端
同样新建一个C#控制台项目:ThriftClient,并将 Thrift.dll 和 MathService.cs 导入到项目中,在Program.cs 中包含:
- 1
- 2
- 1
- 2
修改 Program.cs 中的 Main 函数如下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
运行
首先运行 MathServer,可以看到:
然后运行 MathClient,可以看到:
同时 MathServer 的控制台显示:
完!
参考
- 详细介绍 Apache Thrift - 可伸缩的跨语言服务开发框架(Java):http://www.ibm.com/developerworks/cn/java/j-lo-apachethrift/