通过gRPC,客户端应用可以像调用本地对象一样直接调用另一台不同的机器上服务端应用的方法,使得您能够更容易地创建分布式应用和服务。与许多RPC系统类似,gRPC也是基于以下理念:
定义一个服务,指定其能够被远程调用的方法(包含参数和返回类型)。在服务端实现这个接口,并运行一个gRPC服务器来处理客户端调用。在客户端拥有一个存根能够像服务端一样的方法。
image.png
一个gRPC从开始发起请求到返回总共要经历过序列化,编解码,以及网络传输这些内容。这些东西在我们使用gRPC框架做远程服务调用的时候完全感知不到!至于gRPC的stub之间的连接管理,健康检查,负载均衡,异常重试,优雅启停机,熔断限流等等是需要我们从gRPC源码中获得这些知识的!

参考教程:

https://grpc.io/docs/languages/cpp/quickstart/

安装gRPC

注意:windows平台要使用MSVC编译,MinGW实测编译失败(缺少Linux系统调用)

安装依赖

  1. sudo apt install -y build-essential autoconf libtool pkg-config

下载grpc源码(国内镜像)

  1. git clone -b v1.43.0 https://gitee.com/mirrors/grpc-framework grpc

修改更新submodule(GitHub的submodule下载很慢很慢, 一天都下不下来)

  1. cd grpc
  2. cat .gitmodules // 查看文件里的submodule, 将GitHub改成Gitee
  3. git submodule update --init

安装gRPC

  1. mkdir build
  2. cd build
  3. cmake -DCMAKE_INSTALL_PREFIX=/usr/local ..
  4. make -j2
  5. sudo make install

使用示例

  1. |--- protos
  2. | |--- helloworld.proto -------定义文件,生成.cc或者.h文件
  3. |--- server_cpp
  4. |--- client.cpp
  5. |--- CMakeLists.txt

helloworld.proto

  1. syntax = "proto3";
  2. option java_package = "ex.grpc";
  3. package helloworld;
  4. message Reply {
  5. int32 result = 1;
  6. }
  7. message HelloMessage {
  8. int32 a = 1;
  9. int32 b = 2;
  10. }
  11. service TestServer {
  12. rpc hello_request (HelloMessage) returns (Reply) {}
  13. }

编译命令,自动生成grpc.pb和pb的cc和h文件(CMakeLists.txt中集成如下命令,不需要单独编译):

  1. protoc --cpp_out=. helloworld.proto
  2. protoc --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` helloworld.proto

client

  1. #include <iostream>
  2. #include <memory>
  3. #include <string>
  4. #include <grpcpp/grpcpp.h>
  5. #include "helloworld.grpc.pb.h"
  6. using grpc::Channel;
  7. using grpc::ClientContext;
  8. using grpc::Status;
  9. using helloworld::TestServer;
  10. using helloworld::HelloMessage;
  11. using helloworld::Reply;
  12. class GreeterClient {
  13. public:
  14. GreeterClient(std::shared_ptr<Channel> channel):stub_(TestServer::NewStub(channel)) {}
  15. int say_hello(const std::string& user)
  16. {
  17. HelloMessage request;
  18. Reply reply;
  19. ClientContext context;
  20. //传入两个值,让server计算乘积
  21. request.set_a(21);
  22. request.set_b(22);
  23. Status status = stub_->hello_request(&context, request, &reply);
  24. if (status.ok()) {
  25. return reply.result();
  26. } else {
  27. std::cout << status.error_code() << ": " << status.error_message() << std::endl;
  28. return 0;
  29. }
  30. }
  31. private:
  32. std::unique_ptr<TestServer::Stub> stub_;
  33. };
  34. int main(int argc, char** argv)
  35. {
  36. GreeterClient greeter(grpc::CreateChannel("127.0.0.1:5000", grpc::InsecureChannelCredentials()));
  37. std::string user("world");
  38. int reply = greeter.say_hello(user);
  39. std::cout << "Greeter received: " << reply << std::endl;
  40. return 0;
  41. }

server

  1. #include <string>
  2. #include <grpcpp/grpcpp.h>
  3. #include "helloworld.grpc.pb.h"
  4. using grpc::Server;
  5. using grpc::ServerBuilder;
  6. using grpc::ServerContext;
  7. using grpc::Status;
  8. using helloworld::TestServer;
  9. using helloworld::HelloMessage;
  10. using helloworld::Reply;
  11. class HelloServiceImplementation final : public TestServer::Service {
  12. Status hello_request(ServerContext* context, const HelloMessage* request, Reply* reply) override
  13. {
  14. int a = request->a();
  15. int b = request->b();
  16. reply->set_result(a * b);//返回乘积
  17. return Status::OK;
  18. }
  19. };
  20. int main(int argc, char** argv) {
  21. std::string address("0.0.0.0:5000");
  22. HelloServiceImplementation service;
  23. ServerBuilder builder;
  24. builder.AddListeningPort(address, grpc::InsecureServerCredentials());
  25. builder.RegisterService(&service);
  26. std::unique_ptr<Server> server(builder.BuildAndStart());
  27. std::cout << "Server listening on port: " << address << std::endl;
  28. server->Wait();
  29. return 0;
  30. }

CMakeLists

  1. cmake_minimum_required(VERSION 3.14)
  2. project(grpcdemo)
  3. set(CMAKE_CXX_STANDARD 14)
  4. set(protobuf_MODULE_COMPATIBLE TRUE)
  5. find_package(Protobuf CONFIG REQUIRED)
  6. message(STATUS "Using protobuf ${Protobuf_VERSION}")
  7. set(_PROTOBUF_LIBPROTOBUF protobuf::libprotobuf)
  8. set(_REFLECTION gRPC::grpc++_reflection)
  9. if(CMAKE_CROSSCOMPILING)
  10. find_program(_PROTOBUF_PROTOC protoc)
  11. else()
  12. set(_PROTOBUF_PROTOC $<TARGET_FILE:protobuf::protoc>)
  13. endif()
  14. # Find gRPC installation
  15. # Looks for gRPCConfig.cmake file installed by gRPC's cmake installation.
  16. find_package(gRPC CONFIG REQUIRED)
  17. message(STATUS "Using gRPC ${gRPC_VERSION}")
  18. set(_GRPC_GRPCPP gRPC::grpc++)
  19. if(CMAKE_CROSSCOMPILING)
  20. find_program(_GRPC_CPP_PLUGIN_EXECUTABLE grpc_cpp_plugin)
  21. else()
  22. set(_GRPC_CPP_PLUGIN_EXECUTABLE $<TARGET_FILE:gRPC::grpc_cpp_plugin>)
  23. endif()
  24. # Proto file
  25. get_filename_component(hw_proto "protos/helloworld.proto" ABSOLUTE)
  26. get_filename_component(hw_proto_path "${hw_proto}" PATH)
  27. # Generated sources
  28. set(hw_proto_srcs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.pb.cc")
  29. set(hw_proto_hdrs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.pb.h")
  30. set(hw_grpc_srcs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.grpc.pb.cc")
  31. set(hw_grpc_hdrs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.grpc.pb.h")
  32. add_custom_command(
  33. OUTPUT "${hw_proto_srcs}" "${hw_proto_hdrs}" "${hw_grpc_srcs}" "${hw_grpc_hdrs}"
  34. COMMAND ${_PROTOBUF_PROTOC}
  35. ARGS --grpc_out "${CMAKE_CURRENT_BINARY_DIR}"
  36. --cpp_out "${CMAKE_CURRENT_BINARY_DIR}"
  37. -I "${hw_proto_path}"
  38. --plugin=protoc-gen-grpc="${_GRPC_CPP_PLUGIN_EXECUTABLE}"
  39. "${hw_proto}"
  40. DEPENDS "${hw_proto}")
  41. # Include generated *.pb.h files
  42. include_directories("${CMAKE_CURRENT_BINARY_DIR}")
  43. # hw_grpc_proto
  44. add_library(hw_grpc_proto
  45. ${hw_grpc_srcs}
  46. ${hw_grpc_hdrs}
  47. ${hw_proto_srcs}
  48. ${hw_proto_hdrs})
  49. target_link_libraries(hw_grpc_proto
  50. ${_REFLECTION}
  51. ${_GRPC_GRPCPP}
  52. ${_PROTOBUF_LIBPROTOBUF})
  53. # executable target
  54. foreach(_target client server)
  55. add_executable(${_target} "${_target}.cpp")
  56. target_link_libraries(${_target}
  57. ${_REFLECTION}
  58. ${_GRPC_GRPCPP}
  59. ${_PROTOBUF_LIBPROTOBUF}
  60. hw_grpc_proto)
  61. endforeach()