首先使用Protobuf定义gRPC接口并生成Go代码,接着实现UserService服务端逻辑,最后编写客户端调用GetUser方法获取用户信息。

在微服务架构中,RPC(远程过程调用)是服务间通信的核心方式之一。Golang 以其高性能和简洁的并发模型,成为构建 RPC 服务的热门选择。结合 Protobuf 和 gRPC,可以实现高效、类型安全的接口定义与自动代码生成。本文将带你从零开始设计一个简单的 Golang RPC 接口,并展示如何自动生成服务代码。
定义 Protobuf 接口
使用 Protocol Buffers(Protobuf)定义接口是 gRPC 的标准做法。它支持跨语言、序列化高效,并能自动生成客户端和服务端代码。
首先安装必要的工具:
protoc 编译器 和 protoc-gen-go 插件可以通过以下命令安装:
立即学习“go语言免费学习笔记(深入)”;
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
接下来创建一个 user.proto 文件,定义用户查询接口:
syntax = "proto3";
package service;
option go_package = "./service";
service UserService {
rpc GetUser(GetUserRequest) returns (GetUserResponse);
}
message GetUserRequest {
int64 user_id = 1;
}
message GetUserResponse {
int64 user_id = 1;
string name = 2;
string email = 3;
bool active = 4;
}
这个接口定义了一个 GetUser 方法,接收用户 ID,返回用户信息。
生成 Go 代码
使用 protoc 命令生成 Go 代码:
protoc --go_out=. --go-grpc_out=. user.proto
执行后会生成两个文件:
采用三层架构开发,前台集成了产品在线展示,用户注册、在线调查、在线投稿后台有类别管理\图书管理\订单管理\会员管理\配送范围管理\邮件列表\广告管理\友情链接管理等后台添加图书时自动生成缩略图和文字水印主要参考了petshop的设计架构、使用了Asp.net2.0中很多MemberShip、master等新功能后台管理地址/web/admin/ 超级管理员账号密码均为aspx1特别提示:该系统需要
- user.pb.go:包含消息类型的结构体和序列化代码
- user_grpc.pb.go:包含客户端和服务端的接口定义
生成的服务端接口如下:
type UserServiceServer interface {
GetUser(context.Context, *GetUserRequest) (*GetUserResponse, error)
}
你只需实现这个接口即可。
实现服务端逻辑
创建一个 server.go 文件,实现 UserService 接口:
package main
import (
"context"
"log"
"net"
pb "your-module/service"
"google.golang.org/grpc"
)
type userService struct {
pb.UnimplementedUserServiceServer
}
func (s *userService) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.GetUserResponse, error) {
// 模拟数据库查询
user := &pb.GetUserResponse{
UserId: req.UserId,
Name: "Alice",
Email: "alice@example.com",
Active: true,
}
return user, nil
}
func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
grpcServer := grpc.NewServer()
pb.RegisterUserServiceServer(grpcServer, &userService{})
log.Println("gRPC server running on :50051")
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
启动服务后,它将在 50051 端口监听 gRPC 请求。
编写客户端调用
创建 client.go 测试调用:
package main
import (
"context"
"log"
pb "your-module/service"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func main() {
conn, err := grpc.Dial("localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal("did not connect:", err)
}
defer conn.Close()
client := pb.NewUserServiceClient(conn)
resp, err := client.GetUser(context.Background(), &pb.GetUserRequest{UserId: 123})
if err != nil {
log.Fatal("could not get user:", err)
}
log.Printf("User: %+v", resp)
}
运行客户端,将输出:
User: userId:123 name:"Alice" email:"alice@example.com" active:true通过 Protobuf 定义接口,Golang 能自动生成类型安全的 gRPC 代码,极大提升开发效率和系统稳定性。这套流程适用于大多数微服务场景,配合 Makefile 或脚本可进一步自动化编译过程。
基本上就这些。









