MST

星途 面试题库

面试题:微服务架构中gRPC里Protocol Buffers的基本使用

在微服务架构下,使用gRPC进行通信时,假设要定义一个简单的用户信息服务,用户包含姓名、年龄和邮箱,请用Protocol Buffers定义相关的消息结构,并说明如何使用protoc工具生成对应的代码。
21.1万 热度难度
后端开发微服务架构

知识考点

AI 面试

面试题答案

一键面试

1. 使用Protocol Buffers定义消息结构

syntax = "proto3";

// 定义用户信息消息结构
message User {
  string name = 1;
  int32 age = 2;
  string email = 3;
}

// 定义获取用户请求消息结构
message GetUserRequest {
  string user_id = 1;
}

// 定义获取用户响应消息结构
message GetUserResponse {
  User user = 1;
}

// 定义服务接口
service UserInfoService {
  rpc GetUser(GetUserRequest) returns (GetUserResponse);
}

2. 使用protoc工具生成对应的代码

  1. 安装protoc工具
    • 在不同操作系统上有不同的安装方式。例如在Ubuntu系统上,可以使用以下命令安装:
    sudo apt - get install protobuf - compiler
    
    • 在MacOS上,可以通过Homebrew安装:
    brew install protobuf
    
  2. 生成代码: 假设上述定义的内容保存在user.proto文件中,以生成Go语言代码为例,首先要安装Go的gRPC和protobuf插件:
    go install google.golang.org/protobuf/cmd/protoc - gen - go@latest
    go install google.golang.org/grpc/cmd/protoc - gen - go - grpc@latest
    

然后使用以下命令生成代码:

protoc - I. --go_out=. --go - grpc_out=. user.proto
  • -I.指定输入文件所在目录为当前目录。
  • --go_out=.表示生成Go语言的普通protobuf代码到当前目录。
  • --go - grpc_out=.表示生成Go语言的gRPC服务相关代码到当前目录。

对于其他语言,如Python,首先安装protobufgrpcio - tools库:

pip install protobuf grpcio - tools

然后使用以下命令生成代码:

python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. user.proto
  • --python_out=.生成Python的protobuf代码到当前目录。
  • --grpc_python_out=.生成Python的gRPC服务相关代码到当前目录。