gRPC 项目教程
1. 项目的目录结构及介绍
gRPC 项目的目录结构如下:
grpc/
├── AUTHORS
├── CMakeLists.txt
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── README.md
├── WORKSPACE
├── bazel
├── build_handwritten.yaml
├── cmake
├── doc
├── examples
├── include
├── src
├── test
├── tools
└── third_party
主要目录介绍:
examples/
: 包含各种语言的示例代码。include/
: 包含项目的头文件。src/
: 包含项目的源代码。test/
: 包含项目的测试代码。tools/
: 包含项目使用的工具。third_party/
: 包含项目依赖的第三方库。
2. 项目的启动文件介绍
gRPC 项目的启动文件通常位于 examples/
目录下,具体取决于你使用的语言。以下是一些常见的启动文件示例:
C++ 示例
// examples/cpp/helloworld/greeter_server.cc
#include <iostream>
#include <memory>
#include <string>
#include <grpc++/grpc++.h>
#include "helloworld.grpc.pb.h"
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter;
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;
}
Python 示例
# examples/python/helloworld/greeter_server.py
from concurrent import futures
import time
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051')
server.start()
try:
while True:
time.sleep(60 * 60 * 24)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
serve()
3. 项目的配置文件介绍
gRPC 项目的配置文件通常位于项目的根目录或 cmake/
目录下。以下是一些常见的配置文件示例:
CMake 配置文件
# CMakeLists.txt
cmake_minimum_required(VERSION 3.5.1)
project(grpc)
set(CMAKE_CXX_STANDARD 11)
# 添加源文件和头文件路径
include_directories(include)
# 添加子目录
add_subdirectory(src)
add_subdirectory(test)
Makefile 配置文件
# Makefile
.PHONY: all clean
all:
$(MAKE) -C src
$(MAKE) -C test
clean:
$(MAKE) -C src clean