(一)Apache Thrift 的使用

1. 什麼是RPC框架?

RPC框架,也叫RPC(Remote Procedure Call Protocol)——遠程過程調用協議,它是一種經過網絡從遠程計算機程序上請求服務,而不須要了解底層網絡技術的協議。
例如,兩臺服務器A,B,一個應用部署在A服務器上,想要調用B服務器上應用提供的函數/方法,因爲不在一個內存空間,不能直接調用,須要經過網絡來表達調用的語義和傳達調用的數據。(參考:什麼是 RPC 框架)html

rpc
圖片來源python

過程:nginx

  • Call ID 映射
  • 序列化和反序列化
  • 網絡傳輸

RPC協議假定某些傳輸協議的存在,如TCP或UDP/HTTP,爲通訊程序之間攜帶信息數據。在OSI網絡通訊模型中,RPC跨越了傳輸層和應用層。RPC使得開發包括網絡分佈式多程序在內的應用程序更加容易。c++

總結:服務提供的兩大流派:git

  1. 傳統意義以方法調用爲導向通稱RPC。爲了企業SOA,若干廠商聯合推出webservice,制定了wsdl接口定義,傳輸soap.當互聯網時代,臃腫SOA被簡化爲http+xml/json.可是簡化出現各類混亂。
  2. 以資源爲導向,任何操做無非是對資源的增刪改查,因而統一的REST出現了.

進化的順序: RPC -> SOAP -> RESTfulgithub

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協議層和傳輸層的實現。web

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
相關文章
相關標籤/搜索