gRPC快速开始

Quick start

快速开始

This guide gets you started with gRPC in C++ with a simple working example.

本指南通过一个简单的工作示例开始使用C++中的gRPC。

In the C++ world, there’s no universally accepted standard for managing project dependencies. You need to build and install gRPC before building and running this quick start’s Hello World example.

在C++世界中,没有一个通用的标准来管理项目依赖关系。在构建和运行这个快速入门的HelloWorld示例之前,需要构建并安装gRPC。

Build and locally install gRPC and Protocol Buffers

生成并本地安装gRPC和协议缓冲区

The steps in the section explain how to build and locally install gRPC and Protocol Buffers using cmake. If you’d rather use bazel, see Building from source.

​本节中的步骤解释了如何使用cmake构建和本地安装gRPC和协议缓冲区。如果您更喜欢使用集市,请参阅来源建筑。

Setup
设置

Choose a directory to hold locally installed packages. This page assumes that the environment variable MY_INSTALL_DIR holds this directory path. For example:

选择一个目录来存放本地安装的程序包。本页假定环境变量MY_INSTALL_DIR包含此目录路径。例如:

$ export MY_INSTALL_DIR=$HOME/.local

Ensure that the directory exists:

请确保目录存在:

$ mkdir -p $MY_INSTALL_DIR

Add the local bin folder to your path variable, for example:

将本地bin文件夹添加到路径变量中,例如:

$ export PATH="$MY_INSTALL_DIR/bin:$PATH"
Install cmake
安装cmake

You need version 3.13 or later of cmake. Install it by following these instructions:

需要3.13或更高版本的cmake。按照以下说明进行安装:

  • Linux

    $ sudo apt install -y cmake
    
  • macOS:

    $ brew install cmake
    
  • For general cmake installation instructions, see Installing CMake.

  • ​有关cmake的一般安装说明,请参阅安装cmake。

Check the version of cmake:

检查cmake的版本:

$ cmake --version
cmake version 3.19.6

Under Linux, the version of the system-wide cmake can often be too old. You can install a more recent version into your local installation directory as follows:

在Linux下,系统范围内的cmake版本通常太旧。可以按如下方式将最新版本安装到本地安装目录中:

$ wget -q -O cmake-linux.sh https://github.com/Kitware/CMake/releases/download/v3.19.6/cmake-3.19.6-Linux-x86_64.sh
$ sh cmake-linux.sh -- --skip-license --prefix=$MY_INSTALL_DIR
$ rm cmake-linux.sh
Install other required tools
安装其他所需工具

Install the basic tools required to build gRPC:

安装构建gRPC所需的基本工具:

  • Linux

    $ sudo apt install -y build-essential autoconf libtool pkg-config
    
  • macOS:

    $ brew install autoconf automake libtool pkg-config
    
Clone the grpc repo
克隆grpc repo

Clone the grpc repo and its submodules:

克隆grpc repo及其子模块:

$ git clone --recurse-submodules -b v1.56.0 --depth 1 --shallow-submodules https://github.com/grpc/grpc
Build and install gRPC and Protocol Buffers
生成并安装gRPC和协议缓冲区

While not mandatory, gRPC applications usually leverage Protocol Buffers for service definitions and data serialization, and the example code uses proto3.

​虽然不是强制性的,但gRPC应用程序通常利用协议缓冲区进行服务定义和数据序列化,示例代码使用proto3。

The following commands build and locally install gRPC and Protocol Buffers:

以下命令构建并本地安装gRPC和协议缓冲区:

$ cd grpc
$ mkdir -p cmake/build
$ pushd cmake/build
$ cmake -DgRPC_INSTALL=ON \
      -DgRPC_BUILD_TESTS=OFF \
      -DCMAKE_INSTALL_PREFIX=$MY_INSTALL_DIR \
      ../..
$ make -j 4
$ make install
$ popd
Important
重点

We strongly encourage you to install gRPC locally — using an appropriately set CMAKE_INSTALL_PREFIX — because there is no easy way to uninstall gRPC after you’ve installed it globally.

我们强烈建议在本地安装gRPC,使用适当设置的CMAKE_INSTALL_PREFIX,因为在全局安装gRPC后,没有简单的方法可以卸载它。

More information:

更多信息:

  • You can find a complete set of instructions for building gRPC C++ in Building from source.
  • ​可以在building中从源代码中找到一套完整的构建gRPC C++的说明。
  • For general instructions on how to add gRPC as a dependency to your C++ project, see Start using gRPC C++.
  • ​有关如何将gRPC作为依赖项添加到C++项目的一般说明,请参阅开始使用gRPC C++。

Build the example

构建示例

The example code is part of the grpc repo source, which you cloned as part of the steps of the previous section.

示例代码是grpc repo源代码的一部分,在上一节的步骤中克隆了它。

1.Change to the example’s directory:

1.更改到示例的目录:

$ cd examples/cpp/helloworld

2.Build the example using cmake:

2.使用cmake构建示例:

$ mkdir -p cmake/build
$ pushd cmake/build
$ cmake -DCMAKE_PREFIX_PATH=$MY_INSTALL_DIR ../..
$ make -j 4
Note

Getting build failures? Most issues, at this point, are the result of a faulty installation. Make sure you have the right version of cmake, and carefully recheck your installation.

生成失败?在这一点上,大多数问题都是由于安装错误造成的。确保拥有正确版本的cmake,并仔细重新检查安装。

Try it!

试试看!

Run the example from the example build directory examples/cpp/helloworld/cmake/build:

从示例构建目录examples/cpp/helloworld/cmake/build运行示例:

1.Run the server:

1.运行服务器:

$ ./greeter_server

2.From a different terminal, run the client and see the client output:

2.从另一个终端运行客户端并查看客户端输出:

$ ./greeter_client
Greeter received: Hello world

Congratulations! You’ve just run a client-server application with gRPC.

祝贺您刚刚使用gRPC运行了一个客户端-服务器应用程序。

Update the gRPC service

更新gRPC服务

Now let’s look at how to update the application with an extra method on the server for the client to call. Our gRPC service is defined using protocol buffers; you can find out lots more about how to define a service in a .proto file in Introduction to gRPC and Basics tutorial. For now all you need to know is that both the server and the client stub have a SayHello() RPC method that takes a HelloRequest parameter from the client and returns a HelloReply from the server, and that this method is defined like this:

​现在,让我们看看如何在服务器上使用一个额外的方法来更新应用程序,以便客户端调用。我们的gRPC服务是使用协议缓冲区定义的;可以在gRPC简介和基础教程中找到更多关于如何在.proto文件中定义服务的信息。现在,只需要知道服务器和客户端存根都有一个SayHello()RPC方法,该方法从客户端获取HelloRequest参数并从服务器返回HelloReply,并且该方法的定义如下:

// The greeting 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;
}

Open examples/protos/helloworld.proto and add a new SayHelloAgain() method, with the same request and response types:

​打开examples/protos/helloworld.proto,添加一个新的SayHelloAgain()方法,具有相同的请求和响应类型:

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  // Sends another greeting
  rpc SayHelloAgain (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;
}

Remember to save the file!

记得保存文件!

Regenerate gRPC code

重新生成gRPC代码

Before you can use the new service method, you need to recompile the updated proto file.

在使用新的服务方法之前,需要重新编译更新后的proto文件。

From the example build directory examples/cpp/helloworld/cmake/build, run:

在示例构建目录examples/cpp/helloworld/cmake/build中,运行:

$ make -j 4

This regenerates helloworld.pb.{h,cc} and helloworld.grpc.pb.{h,cc}, which contains the generated client and server classes, as well as classes for populating, serializing, and retrieving our request and response types.

这将重新生成helloworld.pb.{h,cc}和helloworld.crpc.pb.{h,cc},其中包含生成的客户端和服务器类,以及用于填充、序列化和检索我们的请求和响应类型的类。

Update and run the application

更新并运行应用程序

You have new generated server and client code, but you still need to implement and call the new method in the human-written parts of our example application.

有新生成的服务器和客户端代码,但仍需要在示例应用程序的人工编写部分中实现和调用新方法。

Update the server
更新服务器

Open greeter_server.cc from the example’s root directory. Implement the new method like this:

从示例的根目录中打开greeter_server.cc。实现这样的新方法:

class GreeterServiceImpl final : public Greeter::Service {
  Status SayHello(ServerContext* context, const HelloRequest* request,
                  HelloReply* reply) override {
     // ...
  }

  Status SayHelloAgain(ServerContext* context, const HelloRequest* request,
                       HelloReply* reply) override {
    std::string prefix("Hello again ");
    reply->set_message(prefix + request->name());
    return Status::OK;
  }
};
Update the client
更新客户端

A new SayHelloAgain() method is now available in the stub. We’ll follow the same pattern as for the already present SayHello() and add a new SayHelloAgain() method to GreeterClient:

存根中现在提供了一个新的SayHelloAgain()方法。我们将遵循与现有SayHello()相同的模式,并向GreeterClient添加一个新的SayHelloAgain()方法:

class GreeterClient {
 public:
  // ...
  std::string SayHello(const std::string& user) {
     // ...
  }

  std::string SayHelloAgain(const std::string& user) {
    // Follows the same pattern as SayHello.
    HelloRequest request;
    request.set_name(user);
    HelloReply reply;
    ClientContext context;

    // Here we can use the stub's newly available method we just added.
    Status status = stub_->SayHelloAgain(&context, request, &reply);
    if (status.ok()) {
      return reply.message();
    } else {
      std::cout << status.error_code() << ": " << status.error_message()
                << std::endl;
      return "RPC failed";
    }
  }

Finally, invoke this new method in main():

最后,在main()中调用这个新方法:

int main(int argc, char** argv) {
  // ...
  std::string reply = greeter.SayHello(user);
  std::cout << "Greeter received: " << reply << std::endl;

  reply = greeter.SayHelloAgain(user);
  std::cout << "Greeter received: " << reply << std::endl;

  return 0;
}
Run!
运行!

Run the client and server like you did before. Execute the following commands from the example build directory examples/cpp/helloworld/cmake/build:

像以前一样运行客户端和服务器。从示例构建目录examples/cpp/helloworld/cmake/build中执行以下命令:

1.Build the client and server after having made changes:

1.在进行更改后构建客户端和服务器:

$ make -j 4

2.Run the server:

2.运行服务器:

$ ./greeter_server

3.On a different terminal, run the client:

3.在另一个终端上,运行客户端:

$ ./greeter_client

You’ll see the following output:

将看到以下输出:

Greeter received: Hello world
Greeter received: Hello again world
Note

Interested in an asynchronous version of the client and server? You’ll find the greeter_async_{client,server}.cc files in the example’s source directory.


对客户端和服务器的异步版本感兴趣吗?将在示例的源目录中找到greetiner_async_{client,server}.cc文件。

What’s next

接下来是什么

Last modified February 16, 2023: Update Protocol Buffers documentation URL (#1092) (852a744)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值