C++ 使用gRPC入门教程

    gRPC是一个高性能、通用的开源RPC框架,其由Google主要面向移动应用开发并基于HTTP/2协议标准而设计,基于ProtoBuf(Protocol Buffers)序列化协议开发,且支持众多开发语言,能够基于语言自动生成客户端和服务端功能库。   

1.新建工程GrpcClient、GrpcServer和GrpcLibrary

   添加 - 新建项目 - 控制台应用 GrpcClient、GrpcServer。

   添加 - 新建项目 - 类库 GrpcLibrary。 工程中的三个项目情况如下:

   

2.自定义服务

    在项目GrpcLibrary里添加HelloWorld.proto用以生成代码。


   
   
  1. syntax = "proto3";
  2. package GrpcLibrary;
  3. service GrpcService {
  4. rpc SayHello (HelloRequest) returns (HelloReply) {}
  5. }
  6. message HelloRequest {
  7. string name = 1;
  8. }
  9. message HelloReply {
  10. string message = 1;
  11. }

    执行命令

ThirdParty\grpc_build\bin\protoc.exe -IGrpcLibrary --cpp_out GrpcLibrary  GrpcLibrary\HelloWorld.proto --grpc_out GrpcLibrary --plugin=protoc-gen-grpc=ThirdParty\grpc_build\bin\grpc_cpp_plugin.exe
   
   

    命令执行成功后,GrpcLibrary目录下会生成HelloWorld.grpc.pb.cc、HelloWorld.grpc.pb.h、HelloWorld.pb.cc和HelloWorld.pb.h

    

    将其都添加到项目GrpcLibrary中。最后GrpcClient、GrpcServer分别引用类库GrpcLibrary。

3.服务端


   
   
  1. // greeter_server.cc
  2. #include <iostream>
  3. #include <memory>
  4. #include <string>
  5. #include <grpcpp/grpcpp.h>
  6. #ifdef BAZEL_BUILD
  7. #include "examples/protos/helloworld.grpc.pb.h"
  8. #else
  9. #include "HelloWorld.grpc.pb.h"
  10. #endif
  11. using grpc::Server;
  12. using grpc::ServerBuilder;
  13. using grpc::ServerContext;
  14. using grpc::Status;
  15. using GrpcLibrary::HelloRequest;
  16. using GrpcLibrary::HelloReply;
  17. using GrpcLibrary::GrpcService;
  18. // Logic and data behind the server's behavior.
  19. class GreeterServiceImpl final : public GrpcService::Service {
  20. Status SayHello(ServerContext* context, const HelloRequest* request, HelloReply* reply) override
  21. {
  22. std::string prefix("Hello ");
  23. reply-> set_message(prefix + request-> name());
  24. return Status::OK;
  25. }
  26. };
  27. void RunServer() {
  28. std::string server_address("0.0.0.0:50051");
  29. GreeterServiceImpl service;
  30. ServerBuilder builder;
  31. // Listen on the given address without any authentication mechanism.
  32. builder. AddListeningPort(server_address, grpc:: InsecureServerCredentials());
  33. // Register "service" as the instance through which we'll communicate with
  34. // clients. In this case it corresponds to an *synchronous* service.
  35. builder. RegisterService(&service);
  36. // Finally assemble the server.
  37. std::unique_ptr<Server> server(builder.BuildAndStart());
  38. std::cout << "Server listening on " << server_address << std::endl;
  39. // Wait for the server to shutdown. Note that some other thread must be
  40. // responsible for shutting down the server for this call to ever return.
  41. server-> Wait();
  42. }
  43. int main(int argc, char** argv) {
  44. RunServer();
  45. return 0;
  46. }

4.客户端


   
   
  1. // greeter_client.cc
  2. #include <iostream>
  3. #include <memory>
  4. #include <string>
  5. #include <grpcpp/grpcpp.h>
  6. #ifdef BAZEL_BUILD
  7. #include "examples/protos/helloworld.grpc.pb.h"
  8. #else
  9. #include "helloworld.grpc.pb.h"
  10. #endif
  11. using grpc::Channel;
  12. using grpc::ClientContext;
  13. using grpc::Status;
  14. using GrpcLibrary::HelloRequest;
  15. using GrpcLibrary::HelloReply;
  16. using GrpcLibrary::GrpcService;
  17. class GreeterClient {
  18. public:
  19. GreeterClient(std::shared_ptr<Channel> channel)
  20. : stub_(GrpcService:: NewStub(channel)) {}
  21. std::string SayHello(const std::string& user) {
  22. // Data we are sending to the server.
  23. HelloRequest request;
  24. request. set_name(user);
  25. // Container for the data we expect from the server.
  26. HelloReply reply;
  27. // Context for the client. It could be used to convey extra information to
  28. // the server and/or tweak certain RPC behaviors.
  29. ClientContext context;
  30. // The actual RPC.
  31. Status status = stub_-> SayHello(&context, request, &reply);
  32. // Act upon its status.
  33. if (status. ok()) {
  34. return reply. message();
  35. }
  36. else {
  37. std::cout << status. error_code() << ": " << status. error_message()
  38. << std::endl;
  39. return "RPC failed";
  40. }
  41. }
  42. private:
  43. std::unique_ptr<GrpcService::Stub> stub_;
  44. };
  45. int main(int argc, char** argv) {
  46. GreeterClient greeter(grpc::CreateChannel(
  47. "localhost:50051", grpc::InsecureChannelCredentials()));
  48. std::string user("world");
  49. std::string reply = greeter. SayHello(user);
  50. std::cout << "Greeter received: " << reply << std::endl;
  51. return 0;
  52. }

5.测试

   先启动服务的,再启动客户端。

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值