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)用過程十分簡潔析苫,如下圖
前面介紹了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過程峦萎,簡單分解如下
參考
grpc簡介