[RPC]Thrift实例解析

[RPC]Thrift实例解析

内容主要来自thrift官网,以及整合网上的文章,侵删。

这篇博客详细介绍一个官方tutorial的例子

参考链接:

目录树

忽略掉不相关的文件和目录

.
├── cpp
│   ├── CMakeLists.txt
│   ├── CppClient.cpp
│   ├── CppClient.o
│   ├── CppServer.cpp
│   ├── CppServer.o
│   ├── gen-cpp
│   │   ├── Calculator.cpp
│   │   ├── Calculator.h
│   │   ├── Calculator.lo
│   │   ├── Calculator.o
│   │   ├── Calculator_server.skeleton.cpp
│   │   ├── SharedService.cpp
│   │   ├── SharedService.h
│   │   ├── SharedService.lo
│   │   ├── SharedService.o
│   │   ├── SharedService_server.skeleton.cpp
│   │   ├── shared_types.cpp
│   │   ├── shared_types.h
│   │   ├── shared_types.lo
│   │   ├── shared_types.o
│   │   ├── tutorial_constants.cpp
│   │   ├── tutorial_constants.h
│   │   ├── tutorial_constants.lo
│   │   ├── tutorial_constants.o
│   │   ├── tutorial_types.cpp
│   │   ├── tutorial_types.h
│   │   ├── tutorial_types.lo
│   │   └── tutorial_types.o
│   ├── libtutorialgencpp.la
│   ├── Makefile
│   ├── Makefile.am
│   ├── Makefile.in
│   ├── TutorialClient
│   └── TutorialServer
├── Makefile
├── Makefile.am
├── Makefile.in
├── README.md
├── shared.thrift
└── tutorial.thrift

Thrift文件

shared.thrift

// 命名空间,表示适用于某些编程语言,shared指的是路径
namespace cl shared
namespace cpp shared
// 目前不清楚为什么会产生冲突
namespace d share // "shared" would collide with the eponymous D keyword.
namespace dart shared
namespace java shared
namespace perl shared
namespace php shared
namespace haxe shared
namespace netstd shared

// 结构体
struct SharedStruct {
  1: i32 key
  2: string value
}

// 服务
service SharedService {
  SharedStruct getStruct(1: i32 key)
}

tutioral.thrift

// 引入shared.thrift文件
include "shared.thrift"

namespace cl tutorial
namespace cpp tutorial
namespace d tutorial
namespace dart tutorial
namespace java tutorial
namespace php tutorial
namespace perl tutorial
namespace haxe tutorial
namespace netstd tutorial

// 别名
typedef i32 MyInteger

// 常量
const i32 INT32CONSTANT = 9853
// map的值设置方式类似于json
const map<string,string> MAPCONSTANT = {'hello':'world', 'goodnight':'moon'}

// 枚举
enum Operation {
  ADD = 1,
  SUBTRACT = 2,
  MULTIPLY = 3,
  DIVIDE = 4
}

// Operation 来自于上面的定义
// 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
}

// 服务,继承自shared.SharedService,适用extends关键字继承,适用引用文件中定义的类型,需要加上前缀
service Calculator extends shared.SharedService {
   // 返回值为void,需要等待服务器处理完成之后发出回应才能继续执行
   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 zip()

}

根据Thrift文件生成代码

thrift -r --gen cpp tutioral.thrift

生成

├── gen-cpp
│   ├── Calculator.cpp
│   ├── Calculator.h
│   ├── Calculator_server.skeleton.cpp
│   ├── SharedService.cpp
│   ├── SharedService.h
│   ├── SharedService_server.skeleton.cpp
│   ├── shared_types.cpp
│   ├── shared_types.h
│   ├── tutorial_constants.cpp
│   ├── tutorial_constants.h
│   ├── tutorial_types.cpp
│   └── tutorial_types.h

其中

客户端/服务器端代码

cpp/CppClinet.cpp

#include <iostream>

#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>

// Thrift转换得到的文件
#include "../gen-cpp/Calculator.h"

using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

using namespace tutorial;
using namespace shared;

int main() {
  std::shared_ptr<TTransport> socket(new TSocket("localhost", 9090));
  std::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
  std::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
  CalculatorClient client(protocol);

  try {
    transport->open();

    client.ping();
    cout << "ping()" << endl;

    cout << "1 + 1 = " << client.add(1, 1) << endl;

    Work work;
    work.op = Operation::DIVIDE;
    work.num1 = 1;
    work.num2 = 0;

    try {
      client.calculate(1, work);
      cout << "Whoa? We can divide by zero!" << endl;
    } catch (InvalidOperation& io) {
      cout << "InvalidOperation: " << io.why << endl;
      // or using generated operator<<: cout << io << endl;
      // or by using std::exception native method what(): cout << io.what() << endl;
    }

    work.op = Operation::SUBTRACT;
    work.num1 = 15;
    work.num2 = 10;
    int32_t diff = client.calculate(1, work);
    cout << "15 - 10 = " << diff << endl;

    // Note that C++ uses return by reference for complex types to avoid
    // costly copy construction
    SharedStruct ss;
    client.getStruct(ss, 1);
    cout << "Received log: " << ss << endl;

    transport->close();
  } catch (TException& tx) {
    cout << "ERROR: " << tx.what() << endl;
  }
}

cpp/CppServer.cpp

#include <thrift/concurrency/ThreadManager.h>
#include <thrift/concurrency/ThreadFactory.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/server/TSimpleServer.h>
#include <thrift/server/TThreadPoolServer.h>
#include <thrift/server/TThreadedServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>
#include <thrift/TToString.h>

#include <iostream>
#include <stdexcept>
#include <sstream>

#include "../gen-cpp/Calculator.h"

using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::concurrency;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace apache::thrift::server;

using namespace tutorial;
using namespace shared;

class CalculatorHandler : public CalculatorIf {
public:
  CalculatorHandler() = default;

  void ping() override { cout << "ping()" << endl; }

  int32_t add(const int32_t n1, const int32_t n2) override {
    cout << "add(" << n1 << ", " << n2 << ")" << endl;
    return n1 + n2;
  }

  int32_t calculate(const int32_t logid, const Work& work) override {
    cout << "calculate(" << logid << ", " << work << ")" << endl;
    int32_t val;

    switch (work.op) {
    case Operation::ADD:
      val = work.num1 + work.num2;
      break;
    case Operation::SUBTRACT:
      val = work.num1 - work.num2;
      break;
    case Operation::MULTIPLY:
      val = work.num1 * work.num2;
      break;
    case Operation::DIVIDE:
      if (work.num2 == 0) {
        InvalidOperation io;
        io.whatOp = work.op;
        io.why = "Cannot divide by 0";
        throw io;
      }
      val = work.num1 / work.num2;
      break;
    default:
      InvalidOperation io;
      io.whatOp = work.op;
      io.why = "Invalid Operation";
      throw io;
    }

    SharedStruct ss;
    ss.key = logid;
    ss.value = to_string(val);

    log[logid] = ss;

    return val;
  }

  void getStruct(SharedStruct& ret, const int32_t logid) override {
    cout << "getStruct(" << logid << ")" << endl;
    ret = log[logid];
  }

  void zip() override { cout << "zip()" << endl; }

protected:
  map<int32_t, SharedStruct> log;
};

class CalculatorCloneFactory : virtual public CalculatorIfFactory {
 public:
  ~CalculatorCloneFactory() override = default;
  	// // 用于创建连接
    CalculatorIf* getHandler(const ::apache::thrift::TConnectionInfo& connInfo) override
  {
    std::shared_ptr<TSocket> sock = std::dynamic_pointer_cast<TSocket>(connInfo.transport);
    cout << "Incoming connection\n";
    cout << "\tSocketInfo: "  << sock->getSocketInfo() << "\n";
    cout << "\tPeerHost: "    << sock->getPeerHost() << "\n";
    cout << "\tPeerAddress: " << sock->getPeerAddress() << "\n";
    cout << "\tPeerPort: "    << sock->getPeerPort() << "\n";
    return new CalculatorHandler;
  }
    // 释放连接
	void releaseHandler( ::shared::SharedServiceIf* handler) override {
    	delete handler;
  	}
};

int main() {
  TThreadedServer server(
    std::make_shared<CalculatorProcessorFactory>(std::make_shared<CalculatorCloneFactory>()),
    std::make_shared<TServerSocket>(9090), //port
    std::make_shared<TBufferedTransportFactory>(),
    std::make_shared<TBinaryProtocolFactory>());

  cout << "Starting the server..." << endl;
  server.serve();
  cout << "Done." << endl;
  return 0;
}

posted @ 2022-05-06 14:55  xiaowk5516  阅读(81)  评论(0编辑  收藏  举报