(一)Apache Thrift 的使用

1. 什么是RPC框架?

RPC框架,也叫RPC(Remote Procedure Call Protocol)——远程过程调用协议,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议。
例如,两台服务器A,B,一个应用部署在A服务器上,想要调用B服务器上应用提供的函数/方法,由于不在一个内存空间,不能直接调用,需要通过网络来表达调用的语义和传达调用的数据。(参考:什么是 RPC 框架)

rpc
图片来源

过程:

  • Call ID 映射
  • 序列化和反序列化
  • 网络传输

RPC协议假定某些传输协议的存在,如TCP或UDP/HTTP,为通信程序之间携带信息数据。在OSI网络通信模型中,RPC跨越了传输层和应用层。RPC使得开发包括网络分布式多程序在内的应用程序更加容易。

总结:服务提供的两大流派:

  1. 传统意义以方法调用为导向通称RPC。为了企业SOA,若干厂商联合推出webservice,制定了wsdl接口定义,传输soap.当互联网时代,臃肿SOA被简化为http+xml/json.但是简化出现各种混乱。
  2. 以资源为导向,任何操作无非是对资源的增删改查,于是统一的REST出现了.

进化的顺序: RPC -> SOAP -> RESTful

2. Apache Thrift

Thrift是一个跨语言的服务部署框架,最初由Facebook于2007年开发,2008年进入Apache开源项目。Thrift通过IDL(Interface Definition Language,接口定义语言)来定义RPC(Remote Procedure Call,远程过程调用)的接口和数据类型,然后通过thrift编译器生成不同语言的代码(目前支持C++,Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, Smalltalk和OCaml),并由生成的代码负责RPC协议层和传输层的实现。

3. 示例

3.1 WhatTime.thrift文件
namespace cpp ld

struct Example{
    1:i32     number=10,
    2:i64     bigNumber,
    3:double  decimals,
    4:string  name="thrifty"
}

service TimeInterface{
    i32  GetTime(),
    void SetTime()
}

3.2 generate the source from a thrift file

thrift [-r] --gen <language> <Thrift filename>
# -r 可选

3.3 client.cpp

#include "TimeInterface.h"
#include <thrift/transport/TSocket.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TBufferTransports.h>

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

using boost::shared_ptr;

using namespace  ::ld;

int main(int argc, char **argv) {
    int port = 9090;
    boost::shared_ptr<TSocket> socket(new TSocket("localhost", port)); //注意此处的ip和端口
    boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
    boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
    transport->open();

    // 我们的代码写在这里
    TimeInterfaceClient client(protocol);  // 客户端接口,声明于TimeInterface.h中。
    client.SetTime();
    client.GetTime();
    
    transport->close();

    return 0;
}

3.4 makefile

all : server client

server : TimeInterface.cpp  TimeInterface.h  TimeInterface_server.skeleton.cpp  WhatTime_constants.cpp  WhatTime_constants.h  WhatTime_types.cpp  WhatTime_types.h
        g++ -std=c++11 -g -Ithrift -lthrift TimeInterface.cpp  TimeInterface.h  TimeInterface_server.skeleton.cpp  WhatTime_constants.cpp  WhatTime_constants.h  WhatTime_types.cpp  WhatTime_types.h -o server

client: TimeInterface.cpp  TimeInterface.h  WhatTime_constants.cpp  WhatTime_constants.h  WhatTime_types.cpp  WhatTime_types.h client.cpp
        g++ -std=c++11 -g -Ithrift -lthrift TimeInterface.cpp  TimeInterface.h  WhatTime_constants.cpp  WhatTime_constants.h  WhatTime_types.cpp  WhatTime_types.h client.cpp -o client
原文地址:https://www.cnblogs.com/walkinginthesun/p/9559466.html