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ā)的項目。 "縮小"意味著最終用戶在生產(chǎn)應(yīng)用程序中使用技術(shù),并且項目的參與者數(shù)量正常。

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

在云原生應(yīng)用程序中,開發(fā)人員通??缇幊陶Z言、框架和技術(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方法)實現(xiàn)完整的rpc過程,簡單分解如下


簡單分解.png

參考
grpc簡介

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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

友情鏈接更多精彩內(nèi)容