Thrift基础-linux环境搭建+cmake编译

搭建thrift环境,并成功运行。

ubuntu 18.04,Thrift version 0.11.0,cmake version 3.13.0-rc3

搭建Thrift

sudo apt-get install automake bison flex g++ git libboost-all-dev libevent-dev libssl-dev libtool make pkg-config

下载:thrift-0.11.0.tar.gz,进入解压目录:

./configure && make

make install

使用Thrift

  1. 编写thrift_basic.thrift文件

    struct Example{
    	1:i32 number=10,
    	2:i64 bigNumber,
    	3:double decimals,
    	4:string name="thrifty"
    }
    
    service BasicThrift{
    	void SayHelloWorld(1: string msg);
    }
    
  2. 生成C++代码

    thrift -r --gen cpp thrift_basic.thrift
    

    生成的七个文件如下:

    BasicThrift_server.skeleton.cppBasicThrift.cppBasicThrift.hthrift_basic_constants.cppthrift_basic_constants.hthrift_basic_types.cppthrift_basic_types.h

  3. 创建目录结构(主要是清晰的分辨出Client和Server端)

    -client
    	-build
    	-gen-cpp
    		-Client.cpp
    		//拷贝生成的7个文件(BasicThrift_server.skeleton.cpp除外)
    	-CMakeLists.txt
    -server
    	-build
    	-gen-cpp
    		//拷贝生成的7个文件
    	-CMakeLists.txt
    
  4. 新增的文件内容

    1. Client.cpp

      #include 
      #include 
      #include 
      #include 
      #include 
      
      #include "BasicThrift.h"
      
      using namespace apache::thrift;
      using namespace apache::thrift::protocol;
      using namespace apache::thrift::transport;
      
      int main(int argc, char **argv) {
      
          ::apache::thrift::stdcxx::shared_ptr socket(new TSocket("localhost", 9090));
          ::apache::thrift::stdcxx::shared_ptr transport(new TBufferedTransport(socket));
          ::apache::thrift::stdcxx::shared_ptr protocol(new TBinaryProtocol(transport));
          BasicThriftClient client(protocol);
      
          try{
      
              transport->open();
      
              client.SayHelloWorld("From client...");
      
              transport->close();
          } catch (TException& tx) {
              std::cout << "ERROR: " << tx.what() << std::endl;
          }
          return 0;
      }
      
    2. client/CMakeLists.txt

      cmake_minimum_required(VERSION 2.8)
      
      project(BASICTHRIFT)
      
      aux_source_directory(./gen-cpp DIR_SRC)	//一定要注意源代码路径的写法,指向gen-cpp目录
      
      add_executable(thrift_basic_client ${DIR_SRC})
      
      target_link_libraries(thrift_basic_client -lthrift)
      
    3. server/CMakeLists.txt

      cmake_minimum_required(VERSION 2.8)
      
      project(BASICTHRIFT)
      
      aux_source_directory(./gen-cpp DIR_SRC)
      
      add_executable(thrift_basic_server ${DIR_SRC})
      
      target_link_libraries(thrift_basic_server -lthrift)
      

    分别进入各自的build目录,执行:

    cmake ..
    make
    

    分别生成thrift_basic_client和thrift_basic_server的可执行文件

  5. 在控制台中启动server和client

运行效果

这只是一个环境搭建并测试的过程,server端使用的默认生成的BasicThrift_server.skeleton.cpp文件作为服务端的代码,没有写过多的逻辑

Thrift基础-linux环境搭建+cmake编译_第1张图片

你可能感兴趣的:(Thrift)