Thrift跨语言样例开发,thrift跨样例


一、开发环境

  • 1、有一台部署好thrift框架的电脑,本人采用centos5下的thrift框架

(部署步骤可以参看http://blog.csdn.net/san1156/article/details/41146483 )

  • 2、部署的thrift环境需要支持java和c++

二、样例功能

  • 使用c++做服务端,java做客户端,客户端远程调用服务端的服务

三、开发步骤

  • 1、创建接口IDL文件,后缀名为.thrift
文件名:strReversed.thrift
struct StrInfo {
  1: string str,
}
service StrScheduler{
   bool addStr(1:StrInfo str),
   StrInfo getStr()
}
  • 2、编译生成对应语言的头文件
编译语句: 
thrift -gen cpp strReversed.thrift
thrift -gen java strReversed.thrift
  • 3、编译之后,本目录下生成文件夹,类似gen-cpp、gen-java、 gen-py,cd进去,可以看到对应语言的头文件
gen-cpp下文件列表:
-rw-r--r-- 1 root root    281 Apr  9 15:05 strReversed_constants.cpp
-rw-r--r-- 1 root root    375 Apr  9 15:05 strReversed_constants.h
-rw-r--r-- 1 root root   1619 Apr  9 15:05 strReversed_types.cpp
-rw-r--r-- 1 root root   1230 Apr  9 15:05 strReversed_types.h
-rw-r--r-- 1 root root  16679 Apr  9 15:05 StrScheduler.cpp
-rw-r--r-- 1 root root   9410 Apr  9 15:05 StrScheduler.h
-rw-r--r-- 1 root root   4715 May 11 16:13 StrScheduler_server.skeleton.cpp
gen-java下文件列表:
-rw-r--r-- 1 root root 10754 May 11 15:28 StrInfo.java
-rw-r--r-- 1 root root 50847 May 11 15:28 StrScheduler.java
  • 4、利用编译出来的头文件,并编写server代码和client代码
修改文件列表
C++服务端:StrScheduler_server.skeleton.cpp
java客户端:增加文件JavaClient.java
  • 5、利用该语言的编译工具,生成可执行文件

例如:

C++:g++ -DHAVE_NETINET_IN_H -I/usr/local/include/thrift -I/usr/local/include/boost -I../gen-cpp -L/usr/local/lib/ -lthrift strReversed_constants.cpp strReversed_types.cpp StrScheduler.cpp StrScheduler_server.skeleton.cpp -o CppServer

Java:javac *.java

四、测试

五、thrift支持的数据格式

类型           描述
bool          true, false 
byte          8位的有符号整数 
i16           16位的有符号整数 
i32           32位的有符号整数 
i64           64位的有符号整数 
double        64位的浮点数 
string        UTF-8编码的字符串 
binary        字符数组 
struct        结构体 
list          有序的元素列表,类似于STL的vector 
set           无序的不重复元素集,类似于STL的set 
map           key-value型的映射,类似于STL的map 
exception     是一个继承于本地语言的exception基类 
service       服务,包含多个函数接口(纯虚函数)

六、其他

  • 1、C++客户端的开发
    • 1.1、添加文件client.cpp
    • 1.2、编译语句:

g++ -DHAVE_NETINET_IN_H -I/usr/local/include/thrift -I/usr/local/include/boost -I../gen-cpp -L/usr/local/lib/ -lthrift strReversed_constants.cpp strReversed_types.cpp StrScheduler.cpp client.cpp -o CppClient

  • 2、java服务端的开发
    • 2.1、添加文件JavaServer.java和TestImpl.java
    • 2.2、编译语句同上

相关内容