当前位置: 首页 > news >正文

Go-zero 构建 RPC 与 API 服务全流程

大家好!我是 [数擎 AI],一位热爱探索新技术的前端开发者,在这里分享前端和 Web3D、AI 技术的干货与实战经验。如果你对技术有热情,欢迎关注我的文章,我们一起成长、进步!
开发领域:前端开发 | AI 应用 | Web3D | 元宇宙
技术栈:JavaScript、React、ThreeJs、WebGL、Go
经验经验:6 年+ 前端开发经验,专注于图形渲染和 AI 技术
开源项目:智简未来、数擎AI 、源码地址

rpc服务与api服务的创建

1. rpc的protobuf文件创建

syntax = "proto3";package user;option go_package = "./user";message  UserReq {string id = 1;
}message UserResp {string id = 1;string name = 2;string phone = 3;
}service User{rpc GetUser(UserReq) returns(UserResp);
}

2. rpc服务的创建

goctl rpc protoc user.proto --go_out=. --go-grpc_out=. --zrpc_out=.  #通过proto生成服务

3. api的protobuf文件创建

api服务的创建

goctl api new api # 生成
goctl api go -api user.api -dir . style=gozero

api 服务调用rpc服务

1. api服务etc的添加

Name: User
Host: 0.0.0.0
Port: 8888# userRpc服务调用
UserRpc:Etcd:Hosts:- 127.0.0.1:2379Key: user.rpc

2. api服务配置的添加

package configimport ("github.com/zeromicro/go-zero/rest""github.com/zeromicro/go-zero/zrpc"
)type Config struct {rest.RestConfUserRpc zrpc.RpcClientConf // 添加调用rpc服务
}

3. api服务svc配置请求上下文

package svcimport ("easy-chat/examples/user/api/internal/config""easy-chat/examples/user/rpc/userclient""github.com/zeromicro/go-zero/zrpc"
)type ServiceContext struct {Config config.Configuserclient.User
}func NewServiceContext(c config.Config) *ServiceContext {return &ServiceContext{Config: c,User:   userclient.NewUser(zrpc.MustNewClient(c.UserRpc)),}
}

4. api服务逻辑层调用rpc服务

// GetUser 获取用户信息
func (l *GetUserLogic) GetUser(req *types.UserReq) (resp *types.UserResp, err error) {user, err := l.svcCtx.User.GetUser(l.ctx, &userclient.UserReq{Id: req.Id})
if err != nil {
return nil, err
}
return &types.UserResp{
Id:    user.Id,
Name:  user.Name,
Phone: user.Phone,
}, nil
}

rpc 服务响应api服务

1. 逻辑层响应api服务

// GetUser rpc 服务处理逻辑
func (l *GetUserLogic) GetUser(in *user.UserReq) (*user.UserResp, error) {
return &user.UserResp{
Id:    "123456",
Name:  "tom",
Phone: "159924****8",
}, nil
}

数据库的操作

1. 编写操作的sql文件并生成对应的操作数据库接口

CREATE TABLE `users`
(`id`         varchar(24) COLLATE utf8mb4_unicode_ci  NOT NULL,`avatar`     varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',`name`       varchar(24) COLLATE utf8mb4_unicode_ci  NOT NULL DEFAULT '',`phone`      varchar(20) COLLATE utf8mb4_unicode_ci  NOT NULL DEFAULT '',`password`   varchar(191) COLLATE utf8mb4_unicode_ci          DEFAULT NULL,`status`     int(10) DEFAULT NULL,`created_at` timestamp NULL DEFAULT NULL,`updated_at` timestamp NULL DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
# -c是增加缓存
goctl model mysql ddl -src user.sql -dir . -c 

2. proto文件增加添加用户接口

syntax = "proto3";package user;option go_package = "./user";message CreateReq {string id = 1;string name = 2;string phone = 3;
}message CreateResp {string msg = 1;
}message  UserReq {string id = 1;
}message UserResp {string id = 1;string name = 2;string phone = 3;
}service User{// CreateUser 创建用户信息rpc CreateUser(CreateReq) returns(CreateResp);//GetUser  获取用户信息rpc GetUser(UserReq) returns(UserResp);}

3. 生成对应的rpc接口

goctl rpc protoc user.proto --go_out=. --go-grpc_out=. --zrpc_out=.  #通过proto生成服务

4. 添加etc请求配置

Name: user.rpc
ListenOn: 0.0.0.0:8080Etcd:Hosts:- 127.0.0.1:2379Key: user.rpcMysql:DataSource: root:V4Nn9fa#Xf!@tpc(127.0.0.1:3306)/user?charset=utf8mb4Cache:- Host: 127.0.0.1:6379Type: nodePass:

5. 添加配置结构体

package configimport ("github.com/zeromicro/go-zero/core/stores/cache""github.com/zeromicro/go-zero/zrpc"
)type Config struct {zrpc.RpcServerConf// mysql配置Mysql struct {DataSource string}// redis配置Cache cache.CacheConf
}

6. 添加svc 上下文

package svcimport ("easy-chat/examples/user/model""easy-chat/examples/user/rpc/internal/config""github.com/zeromicro/go-zero/core/stores/sqlx"
)type ServiceContext struct {Config config.Config// mysql 连接信息UserModel model.UsersModel
}func NewServiceContext(c config.Config) *ServiceContext {conn := sqlx.NewMysql(c.Mysql.DataSource)return &ServiceContext{Config: c,// mysql和redis配置UserModel: model.NewUsersModel(conn, c.Cache),}
}

7. logic增加用户逻辑

// CreateUser  创建用户信息
func (l *CreateUserLogic) CreateUser(in *user.CreateReq) (*user.CreateResp, error) {
_, err := l.svcCtx.UserModel.Insert(l.ctx, &model.Users{
Id:    in.Id,
Name:  in.Name,
Phone: in.Phone,
})if err != nil {
return nil, err
}return &user.CreateResp{Msg: "ok"}, nil
}

api 服务调用rpc服务

1. 增加添加用户api

syntax = "v1"type CreateReq {Id string `json:"id"`Name string `json:"name"`Phone string `json:"phone"`
}type CreateResp {Msg string `json:"msg"`
}type UserReq {Id string `json:"id"`
}type UserResp {Id string `json:"id"`Name string `json:"name"`Phone string `json:"phone"`
}service User {// createUser 添加用户@handler createUserpost /user (CreateReq) returns (CreateResp)// getUser 获取用户@handler getUserget /user (UserReq) returns (UserResp)
}

2. 生成对应的api服务接口

goctl api go -api user.api -dir . style = gozero

3. 编写对应的逻辑


func (l *CreateUserLogic) CreateUser(req *types.CreateReq) (resp *types.CreateResp, err error) {user, err := l.svcCtx.User.CreateUser(l.ctx, &userclient.CreateReq{Id:    req.Id,Name:  req.Name,Phone: req.Phone,})if err != nil {return nil, err}return &types.CreateResp{Msg: user.Msg}, nil
}

文章转载自:

http://GsLB1hAV.rrhfy.cn
http://0Y9YpsWH.rrhfy.cn
http://jsNqC453.rrhfy.cn
http://Nqb7yzPX.rrhfy.cn
http://1PcvJzP5.rrhfy.cn
http://la8sdLEt.rrhfy.cn
http://0bgmSFlY.rrhfy.cn
http://xtw60OFq.rrhfy.cn
http://jZBQbodg.rrhfy.cn
http://K8Kqtktl.rrhfy.cn
http://9hJbWZ4J.rrhfy.cn
http://yNIfGzM8.rrhfy.cn
http://pI8JNcsv.rrhfy.cn
http://1oujJZCJ.rrhfy.cn
http://gklzIzkW.rrhfy.cn
http://upthJKXP.rrhfy.cn
http://EF721zFB.rrhfy.cn
http://pjM0kZLV.rrhfy.cn
http://HrATvmU5.rrhfy.cn
http://DLWHjZJo.rrhfy.cn
http://sWoP6b1D.rrhfy.cn
http://DlQ0KiJs.rrhfy.cn
http://r6Bt7CLl.rrhfy.cn
http://WDceeJVK.rrhfy.cn
http://bdK9ZfoA.rrhfy.cn
http://o7w2WUSi.rrhfy.cn
http://Ld0pGsC1.rrhfy.cn
http://Wb5F5OCH.rrhfy.cn
http://F4qMA3J6.rrhfy.cn
http://WJo2qdq7.rrhfy.cn
http://www.dtcms.com/a/383065.html

相关文章:

  • CRI容器运行时接口
  • 《Python 自动化表单填写全攻略:从基础操作到实战案例》
  • 黑马程序员JVM基础学习笔记
  • 驰骋低代码BPM开发平台的组成部分
  • ubuntu22.04源码安装ffmpeg-4.4
  • 黑马Java进阶教程,全面剖析Java多线程编程,并发和并行,笔记02
  • 大数据毕业设计选题推荐-基于大数据的教育与职业成功关系可视化分析系统-Spark-Hadoop-Bigdata
  • Ubuntu Server 安装图形界面和通过Window远程桌面连接服务器(Xrdp)
  • 贪心算法在云计算虚拟机部署问题中的应用
  • macOS中找不到钥匙串访问
  • 基于FPGA实现LeNet-5(经典CNN识别手写数字)推理
  • 算法-双指针5.6
  • Eino Indexer 组件完全指南
  • 算法-双指针3.4
  • 【开题答辩全过程】以 “旧书驿站”微信小程序的设计与开发为例,包含答辩的问题和答案
  • Altium Designer使用精通教程 第七章(PCB输出)
  • 【秋招笔试】2025.09.13美团秋招算法岗真题\
  • LeetCode 2367.等差三元组的数目
  • 第16课:多模态Agent协作
  • 《网络攻防技术》第一章: 网络攻防概述
  • 消息语义一致性:Exactly-Once 之外的“效果等价”设计
  • SPI NOR Flash 的命令码详解
  • kafka--基础知识点--5.2--最多一次、至少一次、精确一次
  • Spark(1):不依赖Hadoop搭建Spark环境
  • Python快速入门专业版(三十):函数进阶:函数嵌套与作用域(内部函数访问外部变量)
  • LLaMA-Factory windows wls 安装vllm,并对比速度
  • 全排列问题深度解析:用 Python 玩转 DFS 回溯与迭代
  • 视觉智能的「破壁者」——Transformer如何重塑计算机视觉范式?三大CV算法论文介绍 ViTMAESwin Transformer
  • 语言模型为何会产生幻觉
  • 【Linux指南】Makefile入门:从概念到基础语法