使用thrift做c++,java和python的相互调用 - jinghong - ITeye技术网站

使用thrift做c++,java和python的相互调用

博客分类:linux

linuxthriftc++javapython 

linux上安装thrift见
http://jinghong.iteye.com/blog/1102535
thrift做为跨语言调用的方案有高效,支持语言较多,成熟等优点;代码侵入较强是其弱点。
下面记录以C++做服务器,C++,java和python做客户端的示例,这个和本人现在工作环境吻合,使用多线程长连接的socket来建立高效分布式系统的跨语言调用平台。
遗憾的是目前版本(0.7.0)的C语言还不支持Compact协议,导致在现在的环境中nginx c module调用thrift要使用binary协议。thrift开发团队似乎对C语言不太感冒。
1.定义idl文件acsuser.thrift

Idl代码  
  1. struct User{
  2. 1: string uid,
  3. 2: string uname,
  4. 3: bool usex,
  5. 4: i16 uage,
  6. }
  7. service UserService{
  8. void add(1: User u),
  9. User get(1: string uid),
  10. }
struct User{1: string uid,2: string uname,3: bool usex,4: i16 uage,
}
service UserService{void add(1: User u),User get(1: string uid),
}

2.生成c++,java和python代码框架

Shell代码  
  1. thrift -r --gen cpp acsuser.thrift
  2. thrift -r --gen java acsuser.thrift
  3. thrift -r --gen py acsuser.thrift
thrift -r --gen cpp acsuser.thrift
thrift -r --gen java acsuser.thrift
thrift -r --gen py acsuser.thrift

这时生成子目录gen-cpp,gen-java,gen-py

3.生成C++服务端代码

Shell代码  
  1. cp gen-cpp/UserService_server.skeleton.cpp UserServer.cpp
cp gen-cpp/UserService_server.skeleton.cpp UserServer.cpp

修改UserServer.cpp

C++代码  
  1. #include "UserService.h"
  2. #include <config.h>
  3. //#include <protocol/TBinaryProtocol.h>
  4. #include <protocol/TCompactProtocol.h>
  5. #include <server/TSimpleServer.h>
  6. #include <transport/TServerSocket.h>
  7. #include <transport/TBufferTransports.h>
  8. #include <concurrency/ThreadManager.h>
  9. #include <concurrency/PosixThreadFactory.h>
  10. #include <server/TThreadPoolServer.h>
  11. #include <server/TThreadedServer.h>
  12. using namespace ::apache::thrift;
  13. using namespace ::apache::thrift::protocol;
  14. using namespace ::apache::thrift::transport;
  15. using namespace ::apache::thrift::server;
  16. using namespace ::apache::thrift::concurrency;
  17. using boost::shared_ptr;
  18. class UserServiceHandler : virtual public UserServiceIf {
  19. public:
  20. UserServiceHandler() {
  21. // Your initialization goes here
  22. }
  23. void add(const User& u) {
  24. // Your implementation goes here
  25. printf("uid=%s uname=%s usex=%d uage=%d\n", u.uid.c_str(), u.uname.c_str(), u.usex, u.uage);
  26. }
  27. void get(User& _return, const std::string& uid) {
  28. // Your implementation goes here
  29. _return.uid = "leo1";
  30. _return.uname = "yueyue";
  31. _return.usex = 1;
  32. _return.uage = 3;
  33. printf("uid=%s uname=%s usex=%d uage=%d\n", _return.uid.c_str(), _return.uname.c_str(), _return.usex, _return.uage);
  34. }
  35. };
  36. int main(int argc, char **argv) {
  37. shared_ptr<UserServiceHandler> handler(new UserServiceHandler());
  38. shared_ptr<TProcessor> processor(new UserServiceProcessor(handler));
  39. shared_ptr<TProtocolFactory> protocolFactory(new TCompactProtocolFactory());
  40. shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
  41. shared_ptr<TServerTransport> serverTransport(new TServerSocket(9090));
  42. shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(10);
  43. shared_ptr<PosixThreadFactory> threadFactory = shared_ptr<PosixThreadFactory>(new PosixThreadFactory());
  44. threadManager->threadFactory(threadFactory);
  45. threadManager->start();
  46. printf("start user server...\n");
  47. TThreadPoolServer server(processor, serverTransport, transportFactory, protocolFactory, threadManager);
  48. server.serve();
  49. return 0;
  50. }
#include "UserService.h"
#include <config.h>
//#include <protocol/TBinaryProtocol.h>
#include <protocol/TCompactProtocol.h>
#include <server/TSimpleServer.h>
#include <transport/TServerSocket.h>
#include <transport/TBufferTransports.h>
#include <concurrency/ThreadManager.h>
#include <concurrency/PosixThreadFactory.h>
#include <server/TThreadPoolServer.h>
#include <server/TThreadedServer.h>using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using namespace ::apache::thrift::concurrency;using boost::shared_ptr;class UserServiceHandler : virtual public UserServiceIf {public:UserServiceHandler() {// Your initialization goes here}void add(const User& u) {// Your implementation goes hereprintf("uid=%s uname=%s usex=%d uage=%d\n", u.uid.c_str(), u.uname.c_str(), u.usex, u.uage);}void get(User& _return, const std::string& uid) {// Your implementation goes here_return.uid = "leo1";_return.uname = "yueyue";_return.usex = 1;_return.uage = 3;printf("uid=%s uname=%s usex=%d uage=%d\n", _return.uid.c_str(), _return.uname.c_str(), _return.usex, _return.uage);}};int main(int argc, char **argv) {shared_ptr<UserServiceHandler> handler(new UserServiceHandler());shared_ptr<TProcessor> processor(new UserServiceProcessor(handler));shared_ptr<TProtocolFactory> protocolFactory(new TCompactProtocolFactory());shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());shared_ptr<TServerTransport> serverTransport(new TServerSocket(9090));shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(10);shared_ptr<PosixThreadFactory> threadFactory = shared_ptr<PosixThreadFactory>(new PosixThreadFactory());threadManager->threadFactory(threadFactory);threadManager->start();printf("start user server...\n");TThreadPoolServer server(processor, serverTransport, transportFactory, protocolFactory, threadManager);server.serve();return 0;
}

注意这段代码使用TCompactProtocol,需要#include <config.h>
另外这个是Blocking的多线程服务器

4.生成C++的client文件UserClient.cpp

C++代码  
  1. #include "UserService.h"
  2. #include <config.h>
  3. #include <transport/TSocket.h>
  4. #include <transport/TBufferTransports.h>
  5. #include <protocol/TCompactProtocol.h>
  6. using namespace apache::thrift;
  7. using namespace apache::thrift::protocol;
  8. using namespace apache::thrift::transport;
  9. using boost::shared_ptr;
  10. int main(int argc, char **argv) {
  11. boost::shared_ptr<TSocket> socket(new TSocket("localhost", 9090));
  12. boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
  13. boost::shared_ptr<TProtocol> protocol(new TCompactProtocol(transport));
  14. transport->open();
  15. User u;
  16. u.uid = "leo";
  17. u.uname = "yueyue";
  18. u.usex = 1;
  19. u.uage = 3;
  20. UserServiceClient client(protocol);
  21. client.add(u);
  22. User u1;
  23. client.get(u1,"lll");
  24. transport->close();
  25. printf("uid=%s uname=%s usex=%d uage=%d\n", u1.uid.c_str(), u1.uname.c_str(), u1.usex, u1.uage);
  26. return 0;
  27. }
#include "UserService.h"
#include <config.h>
#include <transport/TSocket.h>
#include <transport/TBufferTransports.h>
#include <protocol/TCompactProtocol.h>using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;using boost::shared_ptr;int main(int argc, char **argv) {boost::shared_ptr<TSocket> socket(new TSocket("localhost", 9090));boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));boost::shared_ptr<TProtocol> protocol(new TCompactProtocol(transport));transport->open();User u;u.uid = "leo";u.uname = "yueyue";u.usex = 1;u.uage = 3;UserServiceClient client(protocol);client.add(u);User u1;client.get(u1,"lll");transport->close();printf("uid=%s uname=%s usex=%d uage=%d\n", u1.uid.c_str(), u1.uname.c_str(), u1.usex, u1.uage);return 0;
}

5.生成Makefile

Makefile代码  
  1. BOOST_DIR = /usr/local/include/boost/
  2. THRIFT_DIR = /usr/local/include/thrift
  3. LIB_DIR = /usr/local/lib
  4. GEN_SRC = ./gen-cpp/acsuser_types.cpp ./gen-cpp/acsuser_constants.cpp ./gen-cpp/UserService.cpp
  5. default: server client
  6. server: UserServer.cpp
  7. g++ -g -o UserServer -I${THRIFT_DIR} -I${BOOST_DIR}  -I./gen-cpp -L${LIB_DIR} -lthrift UserServer.cpp ${GEN_SRC}
  8. client: UserClient.cpp
  9. g++ -g -o UserClient -lm -pthread -lz -lrt -lssl -I${THRIFT_DIR} -I${BOOST_DIR}  -I./gen-cpp -L${LIB_DIR} -lthrift UserClient.cpp ${GEN_SRC}
  10. clean:
  11. $(RM) -r UserServer UserClient
BOOST_DIR = /usr/local/include/boost/
THRIFT_DIR = /usr/local/include/thrift
LIB_DIR = /usr/local/lib
GEN_SRC = ./gen-cpp/acsuser_types.cpp ./gen-cpp/acsuser_constants.cpp ./gen-cpp/UserService.cpp
default: server client
server: UserServer.cppg++ -g -o UserServer -I${THRIFT_DIR} -I${BOOST_DIR}  -I./gen-cpp -L${LIB_DIR} -lthrift UserServer.cpp ${GEN_SRC}
client: UserClient.cppg++ -g -o UserClient -lm -pthread -lz -lrt -lssl -I${THRIFT_DIR} -I${BOOST_DIR}  -I./gen-cpp -L${LIB_DIR} -lthrift UserClient.cpp ${GEN_SRC}
clean:$(RM) -r UserServer UserClient

6.启动c++ server

Shell代码  
  1. ./UserServer
./UserServer

7.测试c++ client

Shell代码  
  1. ./UserClient
./UserClient

8.写java client文件UserClient.java

Java代码  
  1. import org.apache.thrift.TException;
  2. import org.apache.thrift.protocol.TCompactProtocol;
  3. import org.apache.thrift.protocol.TProtocol;
  4. import org.apache.thrift.transport.TFramedTransport;
  5. import org.apache.thrift.transport.TNonblockingSocket;
  6. import org.apache.thrift.transport.TSocket;
  7. import org.apache.thrift.transport.TTransport;
  8. import org.apache.thrift.transport.TTransportException;
  9. //import UserService.Client;
  10. public class UserClient {
  11. private void start() {
  12. try {
  13. TTransport socket = new TSocket("localhost", 9090);
  14. //TTransport transport = new TFramedTransport(socket);
  15. TProtocol protocol = new TCompactProtocol(socket);
  16. UserService.Client client = new UserService.Client(protocol);
  17. socket.open();
  18. System.out.println(client.get("lll"));
  19. User u = new User();
  20. u.uid="leojava";
  21. u.uname="yueyue";
  22. u.usex=true;
  23. u.uage=3;
  24. client.add(u);
  25. socket.close();
  26. } catch (TTransportException e) {
  27. e.printStackTrace();
  28. } catch (TException e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. public static void main(String[] args) {
  33. UserClient c = new UserClient();
  34. c.start();
  35. }
  36. }
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingSocket;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;//import UserService.Client;public class UserClient {private void start() {try {TTransport socket = new TSocket("localhost", 9090);//TTransport transport = new TFramedTransport(socket);TProtocol protocol = new TCompactProtocol(socket);UserService.Client client = new UserService.Client(protocol);socket.open();System.out.println(client.get("lll"));User u = new User();u.uid="leojava";u.uname="yueyue";u.usex=true;u.uage=3;client.add(u);socket.close();} catch (TTransportException e) {e.printStackTrace();} catch (TException e) {e.printStackTrace();}}public static void main(String[] args) {UserClient c = new UserClient();c.start();}
}

编译和运行java client

Shell代码  
  1. javac -classpath /usr/local/lib/libthrift-0.7.0.jar:/usr/local/lib/log4j-1.2.14.jar:/usr/local/lib/commons-logging-1.1.1.jar:/usr/local/lib/slf4j-api-1.5.8.jar UserClient.java ./gen-java/*.java
  2. java -classpath .:./gen-java:/usr/local/lib/libthrift-0.7.0.jar:/usr/local/lib/log4j-1.2.14.jar:/usr/local/lib/commons-logging-1.1.1.jar:/usr/local/lib/slf4j-api-1.5.8.jar:/usr/local/lib/slf4j-log4j12-1.5.8.jar UserClient
javac -classpath /usr/local/lib/libthrift-0.7.0.jar:/usr/local/lib/log4j-1.2.14.jar:/usr/local/lib/commons-logging-1.1.1.jar:/usr/local/lib/slf4j-api-1.5.8.jar UserClient.java ./gen-java/*.java
java -classpath .:./gen-java:/usr/local/lib/libthrift-0.7.0.jar:/usr/local/lib/log4j-1.2.14.jar:/usr/local/lib/commons-logging-1.1.1.jar:/usr/local/lib/slf4j-api-1.5.8.jar:/usr/local/lib/slf4j-log4j12-1.5.8.jar UserClient

9.写Python client文件PythonClient.py

Python代码  
  1. #!/usr/bin/env python
  2. import sys
  3. sys.path.append('./gen-py')
  4. from acsuser import UserService
  5. from acsuser.ttypes import *
  6. from thrift import Thrift
  7. from thrift.transport import TSocket
  8. from thrift.transport import TTransport
  9. from thrift.protocol import TCompactProtocol
  10. # Make socket
  11. transport = TSocket.TSocket('localhost', 9090)
  12. # Buffering is critical. Raw sockets are very slow
  13. transport = TTransport.TBufferedTransport(transport)
  14. # Wrap in a protocol
  15. protocol = TCompactProtocol.TCompactProtocol(transport)
  16. # Create a client to use the protocol encoder
  17. client = UserService.Client(protocol)
  18. # Connect!
  19. transport.open()
  20. # Call Server services
  21. u = client.get('lll')
  22. print 'uid=%s uname=%s usex=%d u.uage=%d' %(u.uid,u.uname,u.usex,u.uage)
  23. u1 = User()
  24. u1.uid='leo'
  25. u1.uname='yueyue'
  26. u1.usex=1
  27. u1.uage=3
  28. client.add(u1)
#!/usr/bin/env python
import sys
sys.path.append('./gen-py')
from acsuser import UserService
from acsuser.ttypes import *
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TCompactProtocol# Make socket
transport = TSocket.TSocket('localhost', 9090)
# Buffering is critical. Raw sockets are very slow
transport = TTransport.TBufferedTransport(transport)
# Wrap in a protocol
protocol = TCompactProtocol.TCompactProtocol(transport)
# Create a client to use the protocol encoder
client = UserService.Client(protocol)
# Connect!
transport.open()
# Call Server services
u = client.get('lll')
print 'uid=%s uname=%s usex=%d u.uage=%d' %(u.uid,u.uname,u.usex,u.uage)u1 = User()
u1.uid='leo'
u1.uname='yueyue'
u1.usex=1
u1.uage=3
client.add(u1)

执行python client代码

Shell代码  
  1. chmod 777 PythonClient.py
  2. ./PythonClient.py
chmod 777 PythonClient.py
./PythonClient.py

  • sample.tar.gz (2.1 KB)
  • 描述: 源文件
  • 下载次数: 43

使用thrift做c++,java和python的相互调用 - jinghong - ITeye技术网站相关推荐

  1. python mobile-hi.codemao.cn_使用thrift做c++,java和python的相互调用

    linux上安装thrift见 http://jinghong.iteye.com/blog/1102535 thrift做为跨语言调用的方案有高效,支持语言较多,成熟等优点:代码侵入较强是其弱点. ...

  2. thrift java长连接_利用thrift在c++、java和python之间相互调用

    转自:http://blog.csdn.net/andy_yf/article/details/7487384 thrift做为跨语言调用的方案有高效,支持语言较多,成熟等优点:代码侵入较强是其弱点. ...

  3. jni c java互相调用_通过JNI实现Java和C++的相互调用

    评论 # re: 通过JNI实现Java和C++的相互调用 2008-07-29 14:14 Always BaNg. 不错,把字符转换也一并讲了吧,比如UTF-8的处理,USC-2与MBCS转换等. ...

  4. [7] 编写Python脚本将Hive的运算结果保存到MySQL数据库中(1) - 摩西莫西 - ITeye技术网站...

    [7] 编写Python脚本将Hive的运算结果保存到MySQL数据库中(1) - 摩西莫西 - ITeye技术网站 [7] 编写Python脚本将Hive的运算结果保存到MySQL数据库中(1) - ...

  5. JAVA与.NET的相互调用——通过Web服务实现相互调用

    JAVA与.NET是现今世界竞争激烈的两大开发媒体,两者语言有很多相似的地方.而在很多大型的开发项目里面,往往需要使用两种语言进行集成开发.而很多的开发人员都会偏向于其中一种语言,在使用集成开发的时候 ...

  6. .Net 与 Java 的服务接口相互调用

    本文介绍.Net 与 Java 相互调用的例子.下面的介绍主要包括三方面:一是通过常用Web服务进行相互调用,二是使用TCP/IP套接字进行相互调用,三是使用Remote实现远程对象相互调用. 首先说 ...

  7. Thrift中实现Java与Python的RPC互相调用

    场景 Thrift介绍以及Java中使用Thrift实现RPC示例: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/1086894 ...

  8. java执行python路径_java调用其它语言脚本(python、js)

    1.背景 之前用开发过程一些功能如图像处理.相似度计算.水印等需要调用算法写的方法,但是算法一般都是用python语言进行开发.所以经常直接用java调用python脚本文件.在网上搜了很多方法也排了 ...

  9. java运行python脚本_java调用python脚本,中文变成问号

    java代码: PythonInterpreter interpreter = new PythonInterpreter(); PySystemState sys = Py.getSystemSta ...

  10. 继甲骨文裁员、Java服软Python后,国产原创IT技术已经成熟,让中国科技不再受制于人!...

    2019独角兽企业重金招聘Python工程师标准>>> "甲骨文创始人拉里·埃里森(Larry Ellison):不能让中国培养比美国还多的工程师!" 世界第二大 ...

最新文章

  1. BAD SLAM | 直接法实时BA+RGBD基准数据集(CVPR2019)
  2. python3 multiprocessing 多进程 列表类型 listproxy 清除内容
  3. python简单代码编写-Python | 编写一个简单的Excel处理脚本
  4. Docker实战:Docker安装部署RabbitMQ
  5. python androidhelper怎么点击屏幕_python:如何模拟helper方法?
  6. Codeforces Round #587 C. White Sheet(思维+计算几何)
  7. 信息安全技术网络安全等级保护定级指南_行业标准 |报业网络安全等级保护定级参考指南V2.0发布,明确保护对象、定级要求...
  8. DotText研究资料整理
  9. windows下如何解决intellij idea控制台中文乱码
  10. php 通讯协议,通讯协议作用
  11. android linux 优化,【「Android」UE手游研发中,如何做好Android内存优化?】|Linux|DEX|腾讯游戏|_傻大方...
  12. Unity,基于layer的碰撞配置
  13. mfc gridctrl 设置某列自动伸长_三明桥梁智能张拉设备数控智能张拉系统全自动智能张拉系统...
  14. MySQL Binlog--事务日志和BINLOG落盘参数对磁盘IO的影响
  15. Java编程:KMP算法
  16. Spring Cloud随记---分布式配置中心初探--一个单节点的配置中心
  17. Mysql 常用函数集
  18. linux下解压bin文件怎么打开方式,安卓手机如何打开.bin文件?
  19. 德标螺纹规格对照表_德标、国标对照表
  20. 三角函数及其之间的关系

热门文章

  1. sqlite具体操作篇
  2. Spring 通过XML配置装配Bean
  3. JS处理数据四舍五入
  4. 18.链表管理内存实现c语言自动释放内存
  5. P(Y|X) 和 P(X,Y)
  6. Elipse中发布一个Maven项目到Tomcat
  7. Jbpm工作流表补数记录
  8. Java开发笔记(一百三十)Swing的选择框
  9. UVa 10061 - How many zero's and how many digits ?
  10. 基于OpenCV的三维数据点的曲面重构_MySurefaceReconstruction