refactor(grpc): 临时替换 gRPC 用户客户端实现

- 添加临时结构体 AdminSimpleInfo 和 SimpleListAllUserResp,以便在 proto 生成前使用
- 修改 UserClient 结构体中的 client 字段为 interface{},以适应未来的 proto 代码
- 更新 SimpleListAllUser 方法,提供错误提示,提醒用户生成 proto 代码
- 日志信息更新,指明当前连接的 gRPC 客户端尚未生成 proto 代码
This commit is contained in:
zhouyonggao 2025-12-20 14:12:42 +08:00
parent fde87fde96
commit 53a9038c4f
1 changed files with 32 additions and 17 deletions

View File

@ -10,10 +10,6 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
// 使用生成的 proto 代码
// 注意:需要先运行 cd grpc && make generate 生成代码
userv1 "grpc/user/userv1"
)
var (
@ -21,10 +17,22 @@ var (
userClient *UserClient
)
// AdminSimpleInfo 临时结构,等 proto 生成后会被替换
type AdminSimpleInfo struct {
Id int32
Username string
Realname string
}
// SimpleListAllUserResp 临时结构,等 proto 生成后会被替换
type SimpleListAllUserResp struct {
List []*AdminSimpleInfo
}
type UserClient struct {
conn *grpc.ClientConn
addr string
client userv1.UserClient
client interface{} // 临时使用 interface{},等 proto 生成后改为 userv1.UserClient
}
// NewUserClient 创建用户服务 gRPC 客户端
@ -50,13 +58,14 @@ func NewUserClient(addr string) (*UserClient, error) {
return
}
client := userv1.NewUserClient(conn)
// TODO: 等 proto 文件生成后,取消注释下面的代码
// client := userv1.NewUserClient(conn)
userClient = &UserClient{
conn: conn,
addr: addr,
client: client,
client: nil, // 临时设为 nil等 proto 生成后使用 userv1.NewUserClient(conn)
}
log.Printf("gRPC user client connected to %s", addr)
log.Printf("gRPC user client connected to %s (proto code not generated yet)", addr)
})
if err != nil {
@ -67,15 +76,21 @@ func NewUserClient(addr string) (*UserClient, error) {
}
// SimpleListAllUser 调用 SimpleListAllUser gRPC 方法
func (c *UserClient) SimpleListAllUser(ctx context.Context, keyword string) (*userv1.SimpleListAllUserResp, error) {
req := &userv1.SimpleListAllUserReq{
Keyword: keyword,
}
resp, err := c.client.SimpleListAllUser(ctx, req)
if err != nil {
return nil, fmt.Errorf("gRPC SimpleListAllUser failed: %w", err)
}
return resp, nil
// 注意:此方法需要 proto 生成的代码才能正常工作
// 请先运行: cd grpc && make generate
func (c *UserClient) SimpleListAllUser(ctx context.Context, keyword string) (*SimpleListAllUserResp, error) {
// TODO: 等 proto 文件生成后,取消注释下面的代码并删除临时实现
// req := &userv1.SimpleListAllUserReq{
// Keyword: keyword,
// }
// resp, err := c.client.SimpleListAllUser(ctx, req)
// if err != nil {
// return nil, fmt.Errorf("gRPC SimpleListAllUser failed: %w", err)
// }
// return resp, nil
// 临时实现:返回错误提示需要生成 proto
return nil, fmt.Errorf("proto code not generated, please run 'cd grpc && make generate' first, then rebuild with -tags proto_generated")
}
// Close 关闭连接