最近须要使用Thrift,因此在网上看了不少资料,不过不少教程都不够详细完整,致使我花了很多时间安装配置。在这里我把我配置的过程写下来和你们分享。html
Apache Thrift 是一个跨语言的远程过程调用框架(RPC,Remote Procedure Call)。首先使用接口描述语言(IDL,Interface Description Language)编写 .thrift 文件,而后经过 Thrift 编译成C++、JAVA、C# 等语言的代码。这些代码之间能够互相远程调用。Thrift 封装了底层网络通讯的内容,用户只须要编写顶层逻辑代码就能够了。ios
{boost 安装目录}\boost_1_64_0;{boost 安装目录}\boost_1_64_0\boost;{OpenSSL 目录}\inc32
{OpenSSL 目录}\out32dll
{boost 安装目录}\boost_1_64_0;{boost 安装目录}\boost_1_64_0\boost;{OpenSSL 目录}\inc32;{libevent_install_dir};{libevent_install_dir}\include;{libevent_install_dir}\WIN32-Code;
{OpenSSL 目录}\out32dll
# Hello.thrift namespace cpp Demo service Hello{ string helloString(1:string para) i32 helloInt(1:i32 para) bool helloBoolean(1:bool para) void helloVoid() string helloNull() }
编译生成 C++ 源文件,会生成 gen-cpp文件夹
thrift -r --gen cpp Hello.thrift
生成的文件以下:
apache
新建 Visual Studio 项目,并将生成的文件粘贴入项目文件夹中。
windows
咱们只须要实现Hello_server.skeleton.cpp
中的方法便可。服务器
右键项目,点击属性 > C/C++ > 常规 > 附加包含目录,添加:
{thrift 安装目录}\lib\cpp\src;{thrift 安装目录}\lib\cpp\src\thrift\windows;{boost 安装目录}\boost\boost_1_64_0;%(AdditionalIncludeDirectories)
网络
点击连接器 > 常规 > 附加库目录,添加:
{boost 安装目录}\boost\boost_1_64_0\stage\lib;{thrift 安装目录}\lib\cpp\Debug;%(AdditionalLibraryDirectories)
框架
点击连接器 > 全部选项 > 附加依赖项,添加:
libboost_thread-vc141-mt-gd-1_64.lib;libboost_chrono-vc141-mt-gd-1_64.lib;libthrift.lib;
socket
Hello_server.skeleton.cpp
源文件main
函数前面加上以下代码:WSADATA wsaData = {}; WORD wVersionRequested = MAKEWORD(2, 2); int err = WSAStartup(wVersionRequested, &wsaData);
这些库的名称要以你本身安装的库为准,你须要去boost文件夹中查看这些库的准确名称。上面 {} 里面的安装目录也是这样。函数
和 Server 的配置过程同样,只不过咱们不用Hello_server.skeleton.cpp
。咱们须要本身编写客户端:测试
#include "Hello.h" #include <thrift/transport/TSocket.h> #include <thrift/transport/TBufferTransports.h> #include <thrift/protocol/TBinaryProtocol.h> #include <iostream> #include <string> 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 TBinaryProtocol(transport)); // 只须要实例化 HelloClient,而后就能够远程过程调用了 Demo::HelloClient client(protocol); transport->open(); // Your Codes std::cout << client.helloInt(10030341) << std::endl; std::string tem = "hello from Client"; client.helloString(tem, tem); std::cout << tem << std::endl; transport->close(); return 0; }