gRPC入門------gRPC簡介

gRPC基本概念

什么是 gRPC囚玫?

gRPC 是一種新式的高性能框架灾常,它通過 RPC (遠(yuǎn)程過程調(diào)用) 改進(jìn)。 在應(yīng)用程序級別,gRPC 簡化了客戶端和后端服務(wù)之間的消息傳遞。 gRPC 源自 Google,是云原生產(chǎn)品/服務(wù)生態(tài)系統(tǒng)的開源 ( 是 () 的一 部分簿姨。 NCF 將 gRPC 作為 一個正在開發(fā)的項(xiàng)目。 "縮小"意味著最終用戶在生產(chǎn)應(yīng)用程序中使用技術(shù)簸搞,并且項(xiàng)目的參與者數(shù)量正常扁位。

典型的 gRPC 客戶端應(yīng)用將公開實(shí)現(xiàn)業(yè)務(wù)操作的本地進(jìn)程內(nèi)函數(shù)。 在此之下攘乒,該本地函數(shù)在遠(yuǎn)程計(jì)算機(jī)上調(diào)用另一個函數(shù)贤牛。 似乎是本地調(diào)用實(shí)質(zhì)上成為對遠(yuǎn)程服務(wù)的透明進(jìn)程外調(diào)用。 RPC 管道提取計(jì)算機(jī)之間的點(diǎn)到點(diǎn)網(wǎng)絡(luò)通信则酝、序列化和執(zhí)行殉簸。

在云原生應(yīng)用程序中,開發(fā)人員通彻炼铮跨編程語言般卑、框架和技術(shù)工作。 這種 互操作性 使消息協(xié)定和跨平臺通信所需的管道變得復(fù)雜爽雄。 gRPC 提供了一個"統(tǒng)一的水平層"來抽象這些問題蝠检。 開發(fā)人員在本機(jī)平臺中編寫代碼,專注于業(yè)務(wù)功能挚瘟,而 gRPC 處理通信管道叹谁。

gRPC 在最常用的開發(fā)堆棧(包括 Java饲梭、JavaScript、C#焰檩、Go憔涉、Swift 和 NodeJS)中提供全面的支持。

調(diào)用過程和示例

官方給出的調(diào)用過程十分簡潔析苫,如下圖


整體示例.png

前面介紹了pb文件的編寫方法兜叨,這里我們通過官方示例,介紹gRPC的調(diào)用過程衩侥。

syntax = "proto3";
// The greeter service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

SayHello便是圖示中的Proto Request方法国旷,HelloRequest和HelloReply是具體的請求響應(yīng)參數(shù)。
我們通過protoc工具生成對應(yīng)的類(C++)

protoc --cpp_out=. helloworld.proto 

grpc-client示例

#include <iostream>
#include <memory>
#include <string>

#include <grpcpp/grpcpp.h>

#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif

using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;

class GreeterClient {
 public:
  GreeterClient(std::shared_ptr<Channel> channel)
      : stub_(Greeter::NewStub(channel)) {}

  // Assembles the client's payload, sends it and presents the response back
  // from the server.
  std::string SayHello(const std::string& user) {
    // Data we are sending to the server.
    HelloRequest request;
    request.set_name(user);

    // Container for the data we expect from the server.
    HelloReply reply;

    // Context for the client. It could be used to convey extra information to
    // the server and/or tweak certain RPC behaviors.
    ClientContext context;

    // The actual RPC.
    Status status = stub_->SayHello(&context, request, &reply);
    
    // Act upon its status.
    if (status.ok()) {
      return reply.message();
    } else {
      std::cout << status.error_code() << ": " << status.error_message()
                << std::endl;
      return "RPC failed";
    }
  }

 private:
  std::unique_ptr<Greeter::Stub> stub_;
};

int main(int argc, char** argv) {
  // Instantiate the client. It requires a channel, out of which the actual RPCs
  // are created. This channel models a connection to an endpoint specified by
  // the argument "--target=" which is the only expected argument.
  // We indicate that the channel isn't authenticated (use of
  // InsecureChannelCredentials()).
  std::string target_str;
  std::string arg_str("--target");
  if (argc > 1) {
    std::string arg_val = argv[1];
    size_t start_pos = arg_val.find(arg_str);
    if (start_pos != std::string::npos) {
      start_pos += arg_str.size();
      if (arg_val[start_pos] == '=') {
        target_str = arg_val.substr(start_pos + 1);
      } else {
        std::cout << "The only correct argument syntax is --target="
                  << std::endl;
        return 0;
      }
    } else {
      std::cout << "The only acceptable argument is --target=" << std::endl;
      return 0;
    }
  } else {
    target_str = "localhost:50051";
  }
  GreeterClient greeter(
      grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials()));
  std::string user("world");
  std::string reply = greeter.SayHello(user);
  std::cout << "Greeter received: " << reply << std::endl;

  return 0;
}

grpc-server示例

#include <iostream>
#include <memory>
#include <string>

#include <grpcpp/ext/proto_server_reflection_plugin.h>
#include <grpcpp/grpcpp.h>
#include <grpcpp/health_check_service_interface.h>

#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;

// Logic and data behind the server's behavior.
class GreeterServiceImpl final : public Greeter::Service {
  Status SayHello(ServerContext* context, const HelloRequest* request,
                  HelloReply* reply) override {
    std::string prefix("Hello ");
    reply->set_message(prefix + request->name());
    return Status::OK;
  }
};

void RunServer() {
  std::string server_address("0.0.0.0:50051");
  GreeterServiceImpl service;

  grpc::EnableDefaultHealthCheckService(true);
  grpc::reflection::InitProtoReflectionServerBuilderPlugin();
  ServerBuilder builder;
  // Listen on the given address without any authentication mechanism.
  builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
  // Register "service" as the instance through which we'll communicate with
  // clients. In this case it corresponds to an *synchronous* service.
  builder.RegisterService(&service);
  // Finally assemble the server.
  std::unique_ptr<Server> server(builder.BuildAndStart());
  std::cout << "Server listening on " << server_address << std::endl;

  // Wait for the server to shutdown. Note that some other thread must be
  // responsible for shutting down the server for this call to ever return.
  server->Wait();
}

int main(int argc, char** argv) {
  RunServer();

  return 0;
}

通過示例可以看到茫死,grpc client通過創(chuàng)建channel(類似于客戶端連接)和stub(pb文件自動創(chuàng)建)完成調(diào)用跪但。
grpc server 通過創(chuàng)建server,注冊自定義的服務(wù)接口(service和rpc方法)實(shí)現(xiàn)完整的rpc過程峦萎,簡單分解如下


簡單分解.png

參考
grpc簡介

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末特漩,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子骨杂,更是在濱河造成了極大的恐慌,老刑警劉巖雄卷,帶你破解...
    沈念sama閱讀 221,331評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件搓蚪,死亡現(xiàn)場離奇詭異,居然都是意外死亡丁鹉,警方通過查閱死者的電腦和手機(jī)妒潭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,372評論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來揣钦,“玉大人雳灾,你說我怎么就攤上這事》氚迹” “怎么了谎亩?”我有些...
    開封第一講書人閱讀 167,755評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長宇姚。 經(jīng)常有香客問我匈庭,道長,這世上最難降的妖魔是什么浑劳? 我笑而不...
    開封第一講書人閱讀 59,528評論 1 296
  • 正文 為了忘掉前任阱持,我火速辦了婚禮,結(jié)果婚禮上魔熏,老公的妹妹穿的比我還像新娘衷咽。我一直安慰自己鸽扁,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,526評論 6 397
  • 文/花漫 我一把揭開白布镶骗。 她就那樣靜靜地躺著桶现,像睡著了一般。 火紅的嫁衣襯著肌膚如雪卖词。 梳的紋絲不亂的頭發(fā)上巩那,一...
    開封第一講書人閱讀 52,166評論 1 308
  • 那天,我揣著相機(jī)與錄音此蜈,去河邊找鬼即横。 笑死,一個胖子當(dāng)著我的面吹牛裆赵,可吹牛的內(nèi)容都是我干的东囚。 我是一名探鬼主播,決...
    沈念sama閱讀 40,768評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼战授,長吁一口氣:“原來是場噩夢啊……” “哼页藻!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起植兰,我...
    開封第一講書人閱讀 39,664評論 0 276
  • 序言:老撾萬榮一對情侶失蹤份帐,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后楣导,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體废境,經(jīng)...
    沈念sama閱讀 46,205評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,290評論 3 340
  • 正文 我和宋清朗相戀三年筒繁,在試婚紗的時候發(fā)現(xiàn)自己被綠了噩凹。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,435評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡毡咏,死狀恐怖驮宴,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情呕缭,我是刑警寧澤堵泽,帶...
    沈念sama閱讀 36,126評論 5 349
  • 正文 年R本政府宣布,位于F島的核電站恢总,受9級特大地震影響落恼,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜离熏,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,804評論 3 333
  • 文/蒙蒙 一佳谦、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧滋戳,春花似錦钻蔑、人聲如沸啥刻。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,276評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽可帽。三九已至,卻和暖如春窗怒,著一層夾襖步出監(jiān)牢的瞬間映跟,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工扬虚, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留努隙,地道東北人。 一個月前我還...
    沈念sama閱讀 48,818評論 3 376
  • 正文 我出身青樓辜昵,卻偏偏與公主長得像荸镊,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子堪置,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,442評論 2 359

推薦閱讀更多精彩內(nèi)容

  • 1躬存、RPC 1.1 什么是RPC RPC(Remote Procedure Call),即遠(yuǎn)程過程調(diào)用舀锨,過程就是方...
    Assassin007閱讀 359評論 0 0
  • 1.簡介 在gRPC中岭洲,客戶端應(yīng)用程序可以直接調(diào)用不同計(jì)算機(jī)上的服務(wù)器應(yīng)用程序上的方法,就像它是本地對象一樣坎匿,使您...
    第八共同體閱讀 1,887評論 0 6
  • GRPC是基于protocol buffers3.0協(xié)議的. 本文將向您介紹gRPC和protocol buffe...
    二月_春風(fēng)閱讀 17,996評論 2 28
  • 本文是gRPC的一個簡單例子钦椭,以protocol buffers 3作為契約類型,使用gRPC自動生成服務(wù)端和客戶...
    ted005閱讀 5,252評論 0 50
  • title: grpc 入門date: 2020-07-21 19:26:19 0. 前言 實(shí)習(xí)期間碑诉,公司項(xiàng)目使用...
    dounine閱讀 1,361評論 0 1