这个thrift的简单示例, 来源于官网 (http://thrift.apache.org/tutorial/cpp), 因为我觉得官网的例子已经很简单了, 所以没有写新的示例, 关于安装的教程, 可以参考https://www.cnblogs.com/albizzia/p/10838646.html, 关于thrift文件的语法, 可以参考: https://www.cnblogs.com/albizzia/p/10838646.html.
thrift文件
首先给出shared.thrift文件的定义:
1/** * 这个Thrift文件包含一些共享定义 */ 2 3namespace cpp shared 4 5struct SharedStruct { 6 1: i32 key 7 2: string value 8} 9 10service SharedService { 11 SharedStruct getStruct(1: i32 key) 12}
然后给出tutorial.thrift的定义:
/** * Thrift引用其他thrift文件, 这些文件可以从当前目录中找到, 或者使用-I的编译器参数指示. * 引入的thrift文件中的对象, 使用被引入thrift文件的名字作为前缀, 例如shared.SharedStruct. */include "shared.thrift"namespace cpp tutorial// 定义别名typedef i32 MyInteger/** * 定义常量. 复杂的类型和结构体使用JSON表示法. */const i32 INT32CONSTANT = 9853const map<string,string> MAPCONSTANT = {'hello':'world', 'goodnight':'moon'}/** * 枚举是32位数字, 如果没有显式指定值,从1开始. */enum Operation { ADD = 1, SUBTRACT = 2, MULTIPLY = 3, DIVIDE = 4}/** * 结构体由一组成员来组成, 一个成员包括数字标识符, 类型, 符号名, 和一个可选的默认值. * 成员可以加"optional"修饰符, 用来表明如果这个值没有被设置, 那么他们不会被串行化到 * 结果中. 不过这个在有些语言中, 需要显式控制. */struct Work { 1: i32 num1 = 0, 2: i32 num2, 3: Operation op, 4: optional string comment,}// 结构体也可以作为异常exception InvalidOperation { 1: i32 whatOp, 2: string why}/** * 服务需要一个服务名, 加上一个可选的继承, 使用extends关键字 */service Calculator extends shared.SharedService { /** * 方法定义和C语言一样, 有返回值, 参数或者一些它可能抛出的异常, 参数列表和异常列表的 * 写法与结构体中的成员列表定义一致. */ void ping(), i32 add(1:i32 num1, 2:i32 num2), i32 calculate(1:i32 logid, 2:Work w) throws (1:InvalidOperation ouch), /** * 这个方法有oneway修饰符, 表示客户段发送一个请求, 然后不会等待回应. Oneway方法 * 的返回值必须是void */ oneway void zip()}
将上述文件放置在同一个文件夹, 然后编译上述的thrift文件:
$ thrift -r --gen cpp tutorial.thrift
生成的文件会出现在gen-cpp子文件夹中, 因为编译时使用了-r参数, 所以shared.thrift也会被编译.
我们可以考虑查看一下thrift编译之后生成的文件, 这里, 我们可以考虑先编译shared.thrift, 编译后, 会生成7个文件, 分别是shared_constants.h, shared_constants.cpp, shared_types.h, shared_types.cpp, SharedService.h, SharedService.cpp, SharedService_server.skeleton.cpp.
我们先查看shared_constants.h和shared.constants.cpp, 这两个文件的命名是原先的thrift文件名, 加上_constants, 换种方式说, 就是xxx.thrift会生成xxx_constants.h和xxx_constants.cpp. 查看一下这两个文件中的内容: 其中会有一个类叫做xxxConstants, 在这个类中, 会将常量作为公有成员, 然后可以通过一个全局变量g_xxx_constants访问. 而xxx_constants.cpp为类函数的定义, 以及全局变量的定义, 应该比较容易理解.
关于shared_types.h和shared_types.cpp文件, 查看shared_types.h中的内容可以看出, shared_types.h中是thrift文件中各种类型的定义, 这个根据文件名应该可以大致猜出. 其中每一个结构体对应两部分, 假设这个结构体叫yyy, 那么第一个部分是结构体_yyy__isset,这个结构体会为thrift中yyy的每个字段添加一个对应的bool值, 名字相同. 第二部分是结构体yyy. 这个结构体中包括thrift中yyy的每个字段, 加上_yyy__isset对象. 这个对象用于yyy读取输入给自身赋值时, 标识某个字段是否被赋值. yyy中的函数主要有如下几个: (1) 默认构造函数 (2) 析构函数 (3) 设置成员变量值的函数 (4) 比较函数 (5) read函数, 用来读取TProtocol对象的内容, 来给自己赋值 (6) write函数, 将自身的值写入到TProtocol的对象中. 最后还有一个swap函数.
关于SharedService.h和SharedService.cpp文件, 查看SharedService.h中的内容可以看出, 这个文件的文件名来自于thrift中的service SharedService, 假设服务名叫做zzz, 那么就会生成对应的zzz.h和zzz.cpp文件, 用来实现这个服务的接口相关的内容. 查看SharedService.h文件, 可以看到如下内容:
(1) class SharedServiceIf用来实现thrift文件中SharedService的接口,
(2) SharedServiceIfFactory用来实现SharedServiceIf的工厂接口, 构建函数为getHandler, 释放函数为releaseHandler, 其中SharedServiceIf在工厂类中定义别名Handler.
(3) SharedServiceIfSingletonFactory是SharedServiceIfFactory的一个具体实现, 用来实现返回单例的SharedServiceIf对象.
(4) SharedServiceNull是SharedServiceIf的不做任何行为的实现.
(5) _SharedService_getStruct_args__isset是SharedService服务的getStruct函数的参数对应的isset类, 用来表示这些参数是否存在.
(6) SharedService_getStruct_args是SharedService服务的getStruct函数的参数对应的类, 用来表示一个服务的函数的参数, 实现内容和thrift文件中的结构体的实现基本一致.
(7) SharedService_getStruct_pargs用处不太清楚.
(8) _SharedService_getStruct_result__isset是SharedService服务的getStruct函数的返回值对应的isset函数, 用来表示返回值是否设置.
(9) SharedService_getStruct_result是SharedService服务的getStruct函数的返回值对应的类, 用来表示一个服务的函数的返回值.
(10) _SharedService_getStruct_presult__isset和SharedService_getStruct_presult用处不太清楚.
(11) SharedServiceClient 是thrift中SharedService服务的客户端实现. SharedServiceClient包括以下内容:
1) 构造函数
2) 获取输入和输出Protocol的函数
3) 服务中定义的方法, 这里是getStruct函数, 以及getStruct函数实现的两个函数,
1 void SharedServiceClient::getStruct(SharedStruct& _return, const int32_t key) 2 { 3 send_getStruct(key); 4 recv_getStruct(_return); 5 }
(12) SharedServiceProcessor为编译器自动生成的对象, 位于Protocol层之上, Server层之下, 实现从输入protocol中读取数据, 然后交给具体的Handler处理, 然后再将结果写入到输出protocol中. 关于这些联系可以参考 https://www.cnblogs.com/albizzia/p/10884907.html.
(13) SharedServiceProcessorFactory是SharedServiceProcessor的工厂类.
(14) SharedServiceMultiface是SharedServiceIf的具体实现, 实现了类似于chain of responsiblity的效果, 也就是依次调用构造函数中传入的多个
SharedServiceIf对象的对应方法. 参考代码:
1void getStruct(SharedStruct& _return, const int32_t key) { 2 size_t sz = ifaces_.size(); 3 size_t i = 0; 4 for (; i < (sz - 1); ++i) { 5 ifaces_[i]->getStruct(_return, key); 6 } 7 ifaces_[i]->getStruct(_return, key); 8 return; 9 }
关于SharedService_server.skeleton.cpp文件, 假设thrift中定义的服务名叫做zzz, 那么这个文件名叫做zzz_server.skeleton.cpp, skeleton的含义是框架, 这个文件的作用是告诉我们如何写出thrift服务器的代码. 这个文件包括两部分:
(1) 类SharedServiceHandler, 这个类用来实现SharedServiceIf, 假设thrift中的服务名叫做zzz, 那么这个类的名字就相对的叫做zzzHandler. 这个类会给出如果你想要实现SharedServiceIf, 那么你需要实现的具体的函数, 对于这个类来说, 需要实现构造函数和getStruct函数, getStruct函数是服务中定义的函数, 有时候, 你也需要实现析构函数吧.
(2) 然后是一个main函数, main函数中的内容, 告诉你怎样实现一个简单的thrift服务器. 你可以考虑把这个文件拷贝一份, 然后根据这个拷贝进行修改, 实现服务器的功能.
如果把shared.thrift和tutorial.thrift一起编译, 那么就会出现14个文件, 每个thrift文件对应7个, 文件的布局和作用和之前说明的一致.
服务端代码
1#include <thrift/concurrency/ThreadManager.h> 2#include <thrift/concurrency/PlatformThreadFactory.h> 3#include <thrift/protocol/TBinaryProtocol.h> 4#include <thrift/server/TSimpleServer.h> 5#include <thrift/server/TThreadPoolServer.h> 6#include <thrift/server/TThreadedServer.h> 7#include <thrift/transport/TServerSocket.h> 8#include <thrift/transport/TSocket.h> 9#include <thrift/transport/TTransportUtils.h> 10#include <thrift/TToString.h> 11#include <thrift/stdcxx.h> 12 13#include <iostream> 14#include <stdexcept> 15#include <sstream> 16 17#include "../gen-cpp/Calculator.h" 18 19using namespace std; 20using namespace apache::thrift; 21using namespace apache::thrift::concurrency; 22using namespace apache::thrift::protocol; 23using namespace apache::thrift::transport; 24using namespace apache::thrift::server; 25 26using namespace tutorial; 27using namespace shared; 28 29class CalculatorHandler : public CalculatorIf { 30public: 31 CalculatorHandler() {} 32 33 void ping() { cout << "ping()" << endl; } 34 35 int32_t add(const int32_t n1, const int32_t n2) { 36 cout << "add(" << n1 << ", " << n2 << ")" << endl; 37 return n1 + n2; 38 } 39 40 int32_t calculate(const int32_t logid, const Work& work) { 41 cout << "calculate(" << logid << ", " << work << ")" << endl; 42 int32_t val; 43 44 switch (work.op) { 45 case Operation::ADD: 46 val = work.num1 + work.num2; 47 break; 48 case Operation::SUBTRACT: 49 val = work.num1 - work.num2; 50 break; 51 case Operation::MULTIPLY: 52 val = work.num1 * work.num2; 53 break; 54 case Operation::DIVIDE: 55 if (work.num2 == 0) { 56 InvalidOperation io; 57 io.whatOp = work.op; 58 io.why = "Cannot divide by 0"; 59 throw io; 60 } 61 val = work.num1 / work.num2; 62 break; 63 default: 64 InvalidOperation io; 65 io.whatOp = work.op; 66 io.why = "Invalid Operation"; 67 throw io; 68 } 69 70 SharedStruct ss; 71 ss.key = logid; 72 ss.value = to_string(val); 73 74 log[logid] = ss; 75 76 return val; 77 } 78 79 void getStruct(SharedStruct& ret, const int32_t logid) { 80 cout << "getStruct(" << logid << ")" << endl; 81 ret = log[logid]; 82 } 83 84 void zip() { cout << "zip()" << endl; } 85 86protected: 87 map<int32_t, SharedStruct> log; 88}; 89 90/* 91 CalculatorIfFactory is code generated. 92 CalculatorCloneFactory is useful for getting access to the server side of the 93 transport. It is also useful for making per-connection state. Without this 94 CloneFactory, all connections will end up sharing the same handler instance. 95*/ 96class CalculatorCloneFactory : virtual public CalculatorIfFactory { 97 public: 98 virtual ~CalculatorCloneFactory() {} 99 virtual CalculatorIf* getHandler(const ::apache::thrift::TConnectionInfo& connInfo) 100 { 101 stdcxx::shared_ptr<TSocket> sock = stdcxx::dynamic_pointer_cast<TSocket>(connInfo.transport); 102 cout << "Incoming connection\n"; 103 cout << "\tSocketInfo: " << sock->getSocketInfo() << "\n"; 104 cout << "\tPeerHost: " << sock->getPeerHost() << "\n"; 105 cout << "\tPeerAddress: " << sock->getPeerAddress() << "\n"; 106 cout << "\tPeerPort: " << sock->getPeerPort() << "\n"; 107 return new CalculatorHandler; 108 } 109 virtual void releaseHandler( ::shared::SharedServiceIf* handler) { 110 delete handler; 111 } 112}; 113 114int main() { 115 TThreadedServer server( 116 stdcxx::make_shared<CalculatorProcessorFactory>(stdcxx::make_shared<CalculatorCloneFactory>()), 117 stdcxx::make_shared<TServerSocket>(9090), //port 118 stdcxx::make_shared<TBufferedTransportFactory>(), 119 stdcxx::make_shared<TBinaryProtocolFactory>()); 120 121 /* 122 // if you don't need per-connection state, do the following instead 123 TThreadedServer server( 124 stdcxx::make_shared<CalculatorProcessor>(stdcxx::make_shared<CalculatorHandler>()), 125 stdcxx::make_shared<TServerSocket>(9090), //port 126 stdcxx::make_shared<TBufferedTransportFactory>(), 127 stdcxx::make_shared<TBinaryProtocolFactory>()); 128 */ 129 130 /** 131 * Here are some alternate server types... 132 133 // This server only allows one connection at a time, but spawns no threads 134 TSimpleServer server( 135 stdcxx::make_shared<CalculatorProcessor>(stdcxx::make_shared<CalculatorHandler>()), 136 stdcxx::make_shared<TServerSocket>(9090), 137 stdcxx::make_shared<TBufferedTransportFactory>(), 138 stdcxx::make_shared<TBinaryProtocolFactory>()); 139 140 const int workerCount = 4; 141 142 stdcxx::shared_ptr<ThreadManager> threadManager = 143 ThreadManager::newSimpleThreadManager(workerCount); 144 threadManager->threadFactory( 145 stdcxx::make_shared<PlatformThreadFactory>()); 146 threadManager->start(); 147 148 // This server allows "workerCount" connection at a time, and reuses threads 149 TThreadPoolServer server( 150 stdcxx::make_shared<CalculatorProcessorFactory>(stdcxx::make_shared<CalculatorCloneFactory>()), 151 stdcxx::make_shared<TServerSocket>(9090), 152 stdcxx::make_shared<TBufferedTransportFactory>(), 153 stdcxx::make_shared<TBinaryProtocolFactory>(), 154 threadManager); 155 */ 156 157 cout << "Starting the server..." << endl; 158 server.serve(); 159 cout << "Done." << endl; 160 return 0; 161}
上述代码应该很容易理解, 在这里就不解释了.
客户端代码
1#include <iostream> 2 3#include <thrift/protocol/TBinaryProtocol.h> 4#include <thrift/transport/TSocket.h> 5#include <thrift/transport/TTransportUtils.h> 6#include <thrift/stdcxx.h> 7 8#include "../gen-cpp/Calculator.h" 9 10using namespace std; 11using namespace apache::thrift; 12using namespace apache::thrift::protocol; 13using namespace apache::thrift::transport; 14 15using namespace tutorial; 16using namespace shared; 17 18int main() { 19 stdcxx::shared_ptr<TTransport> socket(new TSocket("localhost", 9090)); 20 stdcxx::shared_ptr<TTransport> transport(new TBufferedTransport(socket)); 21 stdcxx::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); 22 CalculatorClient client(protocol); 23 24 try { 25 transport->open(); 26 27 client.ping(); 28 cout << "ping()" << endl; 29 30 cout << "1 + 1 = " << client.add(1, 1) << endl; 31 32 Work work; 33 work.op = Operation::DIVIDE; 34 work.num1 = 1; 35 work.num2 = 0; 36 37 try { 38 client.calculate(1, work); 39 cout << "Whoa? We can divide by zero!" << endl; 40 } catch (InvalidOperation& io) { 41 cout << "InvalidOperation: " << io.why << endl; 42 // or using generated operator<<: cout << io << endl; 43 // or by using std::exception native method what(): cout << io.what() << endl; 44 } 45 46 work.op = Operation::SUBTRACT; 47 work.num1 = 15; 48 work.num2 = 10; 49 int32_t diff = client.calculate(1, work); 50 cout << "15 - 10 = " << diff << endl; 51 52 // Note that C++ uses return by reference for complex types to avoid 53 // costly copy construction 54 SharedStruct ss; 55 client.getStruct(ss, 1); 56 cout << "Received log: " << ss << endl; 57 58 transport->close(); 59 } catch (TException& tx) { 60 cout << "ERROR: " << tx.what() << endl; 61 } 62}
从上面的客户端调用来看, 方法调用和本地的类对象的调用很相似, thrift的设计算是很巧妙的. 里面的代码应该不复杂, 所以也不进行具体的讲解了.
查看一下CMakeLists.txt文件:
1cmake_minimum_required(VERSION 2.8) 2 3#include_directories(SYSTEM "${Boost_INCLUDE_DIRS}") 4 5#Make sure gen-cpp files can be included 6include_directories("${CMAKE_CURRENT_BINARY_DIR}") 7include_directories("${CMAKE_CURRENT_BINARY_DIR}/gen-cpp") 8include_directories("${PROJECT_SOURCE_DIR}/lib/cpp/src") 9 10set(tutorialgencpp_SOURCES 11 gen-cpp/Calculator.cpp 12 gen-cpp/SharedService.cpp 13 gen-cpp/shared_constants.cpp 14 gen-cpp/shared_types.cpp 15 gen-cpp/tutorial_constants.cpp 16 gen-cpp/tutorial_types.cpp 17) 18add_library(tutorialgencpp STATIC ${tutorialgencpp_SOURCES}) 19target_link_libraries(tutorialgencpp thrift) 20 21add_custom_command(OUTPUT gen-cpp/Calculator.cpp gen-cpp/SharedService.cpp gen-cpp/shared_constants.cpp gen-cpp/shared_types.cpp gen-cpp/tutorial_constants.cpp gen-cpp/tutorial_types.cpp 22 COMMAND ${THRIFT_COMPILER} --gen cpp -r ${PROJECT_SOURCE_DIR}/tutorial/tutorial.thrift 23) 24 25add_executable(TutorialServer CppServer.cpp) 26target_link_libraries(TutorialServer tutorialgencpp) 27if (ZLIB_FOUND) 28 target_link_libraries(TutorialServer ${ZLIB_LIBRARIES}) 29endif () 30 31add_executable(TutorialClient CppClient.cpp) 32target_link_libraries(TutorialClient tutorialgencpp) 33if (ZLIB_FOUND) 34 target_link_libraries(TutorialClient ${ZLIB_LIBRARIES}) 35endif ()
编译运行, 我这边启动客户端和服务端的命令分别是:
$ LD_LIBRARY_PATH=/usr/local/lib ./TutorialServer$ LD_LIBRARY_PATH=/usr/local/lib ./TutorialClient
注: 上述代码可以在thrift源代码中的tutorial/cpp文件夹找到.