1つの記事でのRPCの分析

1. RPCとは何ですか?RPCはどのような問題を解決できますか?

質問が提起されます:
2つのサービスAとBがあります。AとBは異なるサーバーにデプロイされています。AはBサービスの合計関数sumfuncを呼び出す必要があります。これを実現するにはどうすればよいですか?


RPCリモートプロシージャコール(リモートプロシージャコール)は、リモートマシンの以前の通信の問題に対処するために使用されるソリューションです。RPCの出発点は、ネットワークプロトコル層の面倒なプロトコルを保護し、最も直接的なリモート呼び出しAPIをユーザーに公開することです。 。簡単に理解すると、あるノードが別のノードによって提供されるサービスを要求します。

RPCを詳細に理解するには、まず「手順」の概念を理解します。

1)同じプロセス、同じスレッドの内部関数呼び出し
これは一般的な関数呼び出しであり、スレッド内でネストされた関数を使用します。オペレーティングシステムの基本的な知識によれば、コンパイラはコンパイルプロセス中に関数呼び出しの場所で関数実行のエントリアドレスを提供し、これを介してスレッドのアドレス空間で呼び出されて実行される対応する関数を見つけます住所。基本的に市内通話。


2)
異なるプロセス間の関数呼び出し異なるプロセス間の関数呼び出しは、実際には異なるプロセス間の通信の問題、つまりIPCです。
IPC通信には多くの方法がありますが、より一般的な方法は、パイプ、共有メモリ、メッセージキューなどです。本質的に、関数呼び出しはローカル呼び出しです。これは、それらのアクセスが同じマシン上で同じメモリアクセススペースにあるためです。


3)異なるマシンでのクロスネットワーク関数呼び出し
このメソッドは、リモート呼び出しとも呼ばれます。リモート呼び出しの従来の使用法は、ソケットを使用することです。ユーザーが独自のソケットを作成すると、クライアントとサーバーは特定のデータストリームプロトコルに従って通信し、関数呼び出しを完了します。

ある意味、RPCもこのようなものです。関数呼び出しの機能にはネットワークプロトコルとデータシリアル化ロジックが必要であり、開発が困難であり、常に改善されているため、この種のリモート呼び出しは明らかにコード開発で多くの作業を増やします。


2. RPCの原則は何ですか?

2.1RPCフレームワーク

ここに画像の説明を挿入


2.2RPCコア機能フレームワーク

RPCはクライアント/サーバーモデルを採用しています。リクエスターはクライアントであり、サービスプロバイダーはサーバーです。
RPCのコア機能は、クライアント、クライアントスタブ、ネットワーク伝送モジュール、サーバースタッド、サーバーなどの5つの部分で構成されています。
ここに画像の説明を挿入

  • クライアント:サービスの呼び出し元。
  • クライアントスタブ:サーバーアドレス情報を保存し、クライアントの要求パラメーター情報をネットワーク情報にパッケージ化してから、ネットワーク送信を介してサーバーに送信します。
  • サーバースタブ:クライアントから送信された解凍要求メッセージを受信し、ローカルサービスを呼び出して処理します。
  • サーバー:サービスの実際のプロバイダー。
  • ネットワークサービス:基盤となる送信。TCPまたはHTTPの場合があります。

ローカル呼び出しでは、関数本体は関数ポインタによって直接指定されますが、リモート呼び出しでは、2つのプロセスのアドレス空間が完全に異なるため、関数ポインタは機能しません。このとき、サービスアドレッシングはCall IDマッピングを使用でき、クライアントとサーバーは対応する関数と呼び出しIDのテーブルを維持します(すべての関数は独自のIDを持っている必要があります)。

クライアントは、リモートプロシージャコールを行うときにこのIDを添付する必要があります。クライアントがリモート呼び出しを行う必要がある場合、クライアントはこのテーブルをチェックして対応する呼び出しIDを見つけ、それをサーバーに渡します。サーバーはテーブルもチェックして、クライアントが呼び出す必要のある関数を判別してから、対応する関数のコード。

サーバーのaddAge関数を呼び出すクライアントを例にとると、プロセスは次のとおりです。

// Client端 
//   Student student = Call(ServerAddr, addAge, student)
1. 将这个调用映射为Call ID。
2. 将Call ID,student(params)序列化,以二进制形式打包
3.2中得到的数据包发送给ServerAddr,这需要使用网络传输层
4. 等待服务器返回结果
5. 如果服务器调用成功,那么就将结果反序列化,并赋给student,年龄更新

// Server端
1. 在本地维护一个Call ID到函数指针的映射call_id_map,可以用Map<String, Method> callIdMap
2. 等待客户端请求
3. 得到一个请求后,将其数据包反序列化,得到Call ID
4. 通过在callIdMap中查找,得到相应的函数指针
5. 将student(params)反序列化后,在本地调用addAge()函数,得到结果
6. 将student结果序列化后通过网络返回给Client


2.3RPCコアネットワーク伝送プロトコル

1)
TCPプロトコルに基づくRPC TCPプロトコルは、プロトコルスタックの下位層にあり、プロトコルフィールドをより柔軟にカスタマイズし、ネットワークオーバーヘッドを削減し、パフォーマンスを向上させ、スループットと同時実行性を向上させることができます。


2)HTTPプロトコルに基づくRPC
は、JSONおよびXML形式の要求または応答データを使用できます。HTTPプロトコルは上位層のプロトコルです。同じ内容のメッセージを送信する場合、HTTPプロトコルを使用した送信に使用されるバイト数は、TCPプロトコルを使用した送信に使用されるバイト数よりも多くなります。


三、RPC vs Restful

RPCとRestfulは次元の概念ではなく、RPCにはより広い範囲の次元が含まれます。

1)RPCスタイルのURLとRestfulスタイルのURLの比較
RPC url:/queryOrder?orderId=123
Restful url:Get /order?orderId=123

2)RPCはプロセス指向であり、Restfulはリソース指向です
。RestfulスタイルのURLは、単純さと読みやすさの点で優れています。
ここに画像の説明を挿入
ここに画像の説明を挿入
Restfulは主に外部の公共サービス(Android、IOSクライアント)を提供します。これは、外部サービスを理解しやすくします。
RPCは、内部サービス間の呼び出しによく使用されます。


4.一般的に使用されるRPCは何ですか?

1)gRPC
gRPCは、GoogleのHTTP 2.0プロトコルに基づいてGoogleが公開しているオープンソースソフトウェアであり、多くの一般的なプログラミング言語をサポートしています。RPCフレームワークは、HTTPプロトコルに基づいて実装されます。


2)Thrift
Thriftは、FacebookのオープンソースRPCフレームワークであり、主にクロスランゲージサービス開発フレームワークです。ユーザーはその上で二次開発を実行するだけでよく、アプリケーションは基盤となるRPC通信に対して透過的です。ただし、特定の分野の言語を学ぶ必要があるユーザーには、依然として一定のコストがかかります。


3)Dubbo
Dubboは、Alibaba Groupがオープンソース化した非常に有名なRPCフレームワークであり、多くのインターネット企業やエンタープライズアプリケーションで広く使用されています。プロトコルとシリアル化フレームワークの両方を接続および切断できることは、非常に特徴的な機能です。


4)BRPC
BRPCはBaiduのオープンソースPRCフレームワークです。「brpc」は「より良いRPC」を意味します。Baiduのアプリケーションの例は数百万あります。C++言語で実装されており、C / C ++プログラマーが学ぶのに非常に適しています。


5、RPC使用(BRPC)

5.1BRPCコンパイル

コンパイル手順のリファレンス:https://github.com/apache/incubator-brpc/blob/master/docs/cn/getting_started.md
protobufはライブラリのバージョンに依存し、現在protobuf3.0をサポートしていないことに注意してください。 。

(1)コマンドインストール依存パッケージ
BRPCは、gflags、protobuf、leveldbの3つのオープンソースライブラリに依存する必要があります。

  • gflagsは、Linuxコマンドラインなどのパラメーターを指定するために使用されます。
  • protobufは、シリアル化と逆シリアル化、およびそのrpc定義に使用されます。
  • Leveldbはストレージに使用されます。

一般的なdeps、gflags、protobuf、leveldbをインストールします

sudo apt-get install -y git g++ make libssl-dev libgflags-dev libprotobuf-dev libprotoc-dev protobuf-compiler libleveldb-dev

leveldbが必要な場合

sudo apt-get install -y libsnappy-dev


(2)ソースコードのインストールに依存するパッケージソースコードをインストールするとき
は、パスを次のように設定します。--prefix=/usr

ソースからglogをインストールします

$ git clone https://github.com/boboxxd/glog.git
$ cd glog
$ ./autogen.sh && ./configure --prefix=/usr && make && sudo make install


(3)BRPCをコンパイルする

$  git clone https://gitee.com/baidu/BRPC.git
$  cd BRPC
$  sh config_brpc.sh --headers=/usr/include --libs=/usr/lib --with-glog
$  make

オプション

  • glogをサポートし、以下を--with-glog追加します
  • シンボルのデバッグをサポートしたくないので、次を--nodebugsymbols追加します
  • thriftをサポートし、:--with-thrift追加し、最初にthriftをインストールします。


5.2ランニングケース

Baiduには、gitで直接使用できる多くのケースがあります。ここでは、読み取りと書き込みの最も単純な例を使用します。

$ cd example/echo_c++
$ make
$ ./echo_server &
$ ./echo_client

何ここでコンパイルされ、静的リンクです。あなたが最初に、動的リンクを使用したい場合はmake clean、その後、LINK_SO=1 make実行可能ファイルを動的リンクを生成します。


5.3RPC呼び出しの例

1)サーバーのソースコード

// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

// A server to receive EchoRequest and send back EchoResponse.

#include <gflags/gflags.h>
#include <butil/logging.h>
#include <brpc/server.h>
#include "echo.pb.h"

DEFINE_bool(echo_attachment, true, "Echo attachment as well");
DEFINE_int32(port, 8000, "TCP Port of this server");
DEFINE_int32(idle_timeout_s, -1, "Connection will be closed if there is no "
             "read/write operations during the last `idle_timeout_s'");
DEFINE_int32(logoff_ms, 2000, "Maximum duration of server's LOGOFF state "
             "(waiting for client to close connection before server stops)");

// Your implementation of example::EchoService
// Notice that implementing brpc::Describable grants the ability to put
// additional information in /status.
namespace example {
    
    
class EchoServiceImpl : public EchoService {
    
    
public:
    EchoServiceImpl() {
    
    };
    virtual ~EchoServiceImpl() {
    
    };
    virtual void Echo(google::protobuf::RpcController* cntl_base,
                      const EchoRequest* request,
                      EchoResponse* response,
                      google::protobuf::Closure* done) {
    
    
        // This object helps you to call done->Run() in RAII style. If you need
        // to process the request asynchronously, pass done_guard.release().
        brpc::ClosureGuard done_guard(done);

        brpc::Controller* cntl =
            static_cast<brpc::Controller*>(cntl_base);

        // The purpose of following logs is to help you to understand
        // how clients interact with servers more intuitively. You should 
        // remove these logs in performance-sensitive servers.
        LOG(INFO) << "Received request[log_id=" << cntl->log_id() 
                  << "] from " << cntl->remote_side() 
                  << " to " << cntl->local_side()
                  << ": " << request->message()
                  << " (attached=" << cntl->request_attachment() << ")";

        // Fill response.
        response->set_message(request->message());

        // You can compress the response by setting Controller, but be aware
        // that compression may be costly, evaluate before turning on.
        // cntl->set_response_compress_type(brpc::COMPRESS_TYPE_GZIP);

        if (FLAGS_echo_attachment) {
    
    
            // Set attachment which is wired to network directly instead of
            // being serialized into protobuf messages.
            cntl->response_attachment().append(cntl->request_attachment());
        }
    }
};
}  // namespace example

int main(int argc, char* argv[]) 
{
    
    
    // Parse gflags. We recommend you to use gflags as well.
    GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);

    // Generally you only need one Server.
    brpc::Server server;

    // Instance of your service.
    example::EchoServiceImpl echo_service_impl;

    // Add the service into server. Notice the second parameter, because the
    // service is put on stack, we don't want server to delete it, otherwise
    // use brpc::SERVER_OWNS_SERVICE.
    if (server.AddService(&echo_service_impl, 
                          brpc::SERVER_DOESNT_OWN_SERVICE) != 0) {
    
    
        LOG(ERROR) << "Fail to add service";
        return -1;
    }

    // Start the server.
    brpc::ServerOptions options;
    options.idle_timeout_sec = FLAGS_idle_timeout_s;
    if (server.Start(FLAGS_port, &options) != 0) {
    
    
        LOG(ERROR) << "Fail to start EchoServer";
        return -1;
    }

    // Wait until Ctrl-C is pressed, then Stop() and Join() the server.
    server.RunUntilAskedToQuit();
    return 0;
}

2)クライアントのソースコード

// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

// A client sending requests to server every 1 second.

#include <gflags/gflags.h>
#include <butil/logging.h>
#include <butil/time.h>
#include <brpc/channel.h>
#include "echo.pb.h"

DEFINE_string(attachment, "", "Carry this along with requests");
DEFINE_string(protocol, "baidu_std", "Protocol type. Defined in src/brpc/options.proto");
DEFINE_string(connection_type, "", "Connection type. Available values: single, pooled, short");
DEFINE_string(server, "0.0.0.0:8000", "IP Address of server");
DEFINE_string(load_balancer, "", "The algorithm for load balancing");
DEFINE_int32(timeout_ms, 100, "RPC timeout in milliseconds");
DEFINE_int32(max_retry, 3, "Max retries(not including the first RPC)"); 
DEFINE_int32(interval_ms, 1000, "Milliseconds between consecutive requests");

int main(int argc, char* argv[]) {
    
    
    // Parse gflags. We recommend you to use gflags as well.
    GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);
    
    // A Channel represents a communication line to a Server. Notice that 
    // Channel is thread-safe and can be shared by all threads in your program.
    brpc::Channel channel;
    
    // Initialize the channel, NULL means using default options.
    brpc::ChannelOptions options;
    options.protocol = FLAGS_protocol;
    options.connection_type = FLAGS_connection_type;
    options.timeout_ms = FLAGS_timeout_ms/*milliseconds*/;
    options.max_retry = FLAGS_max_retry;
    if (channel.Init(FLAGS_server.c_str(), FLAGS_load_balancer.c_str(), &options) != 0) {
    
    
        LOG(ERROR) << "Fail to initialize channel";
        return -1;
    }

    // Normally, you should not call a Channel directly, but instead construct
    // a stub Service wrapping it. stub can be shared by all threads as well.
    example::EchoService_Stub stub(&channel);

    // Send a request and wait for the response every 1 second.
    int log_id = 0;
    while (!brpc::IsAskedToQuit()) {
    
    
        // We will receive response synchronously, safe to put variables
        // on stack.
        example::EchoRequest request;
        example::EchoResponse response;
        brpc::Controller cntl;

        request.set_message("hello world");

        cntl.set_log_id(log_id ++);  // set by user
        // Set attachment which is wired to network directly instead of 
        // being serialized into protobuf messages.
        cntl.request_attachment().append(FLAGS_attachment);

        // Because `done'(last parameter) is NULL, this function waits until
        // the response comes back or error occurs(including timedout).
        stub.Echo(&cntl, &request, &response, NULL);
        if (!cntl.Failed()) {
    
    
            LOG(INFO) << "Received response from " << cntl.remote_side()
                << " to " << cntl.local_side()
                << ": " << response.message() << " (attached="
                << cntl.response_attachment() << ")"
                << " latency=" << cntl.latency_us() << "us";
        } else {
    
    
            LOG(WARNING) << cntl.ErrorText();
        }
        usleep(FLAGS_interval_ms * 1000L);
    }

    LOG(INFO) << "EchoClient is going to quit";
    return 0;
}

BRPCプロジェクトには例が付属しています:BRPC / example

おすすめ

転載: blog.csdn.net/locahuang/article/details/112917768