gRPC(Google Remote Procedure Call)是一种高性能、开源和通用的RPC框架,用于在不同服务之间进行通信。它基于HTTP/2协议,支持多种编程语言。Protocol Buffers(protobuf)是Google开发的一种数据序列化协议,用于结构化数据的存储和交换。
.proto
文件是protobuf的定义文件,描述了服务接口和消息结构。通过编译.proto
文件,可以生成不同编程语言的客户端和服务端代码。
.proto
文件:.proto
文件:greeter.pb.h
和 greeter.pb.cc
:protobuf生成的C++代码。greeter.grpc.pb.h
和 greeter.grpc.pb.cc
:gRPC生成的C++代码。grpc_cpp_plugin
:grpc_cpp_plugin
是否在系统路径中。.proto
文件的语法是否正确。以下是一个简单的gRPC服务端和客户端的示例代码:
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "greeter.grpc.pb.h"
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using example::Greeter;
using example::HelloReply;
using example::HelloRequest;
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;
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
server->Wait();
}
int main(int argc, char** argv) {
RunServer();
return 0;
}
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "greeter.grpc.pb.h"
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using example::Greeter;
using example::HelloReply;
using example::HelloRequest;
class GreeterClient {
public:
GreeterClient(std::shared_ptr<Channel> channel)
: stub_(Greeter::NewStub(channel)) {}
void SayHello(const std::string& user) {
HelloRequest request;
request.set_name(user);
HelloReply reply;
ClientContext context;
Status status = stub_->SayHello(&context, request, &reply);
if (status.ok()) {
std::cout << "Greeter received: " << reply.message() << std::endl;
} else {
std::cout << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
}
}
private:
std::unique_ptr<Greeter::Stub> stub_;
};
int main(int argc, char** argv) {
GreeterClient greeter(grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials()));
std::string user("world");
greeter.SayHello(user);
return 0;
}
领取专属 10元无门槛券
手把手带您无忧上云