【Go语言实战】 (15) Gin+gRPC 微服务实现备忘录 (下) | 备忘录模块
【摘要】
文章目录
写在前面源码地址:1. 备忘录部分1.1 proto模块定义1.2 数据库结构定义1.3 接入ETCD
2. 网关接入2.1 服务接入2.2 controller
3. 测试返回...
写在前面
和上篇文章类似,这次我们完成具体功能部分。
源码地址:
https://github.com/CocaineCong/gRPC-todoList
1. 备忘录部分
1.1 proto模块定义
taskModel.proto
syntax="proto3";
package pb;
option go_package = "/internal/service;service";
message TaskModel {
// @inject_tag: json:"favorite_id"
uint32 TaskID=1;
// @inject_tag: json:"user_id"
uint32 UserID=2;
// @inject_tag: json:"status"
uint32 Status=3;
// @inject_tag: json:"title"
string Title=4;
// @inject_tag: json:"content"
string Content=5;
// @inject_tag: json:"start_time"
uint32 StartTime=6;
// @inject_tag: json:"end_time"
uint32 EndTime=7;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
taskService.proto
syntax="proto3";
package pb;
import "taskModels.proto";
option go_package = "/internal/service;service";
message TaskRequest{
uint32 TaskID=1;
uint32 UserID=2;
uint32 Status=3;
string Title=4;
string Content=5;
uint32 StartTime=6;
uint32 EndTime=7;
}
message TasksDetailResponse{
repeated TaskModel TaskDetail=1;
uint32 Code=2;
}
message CommonResponse{
uint32 Code=1;
string Msg=2;
string Data=3;
}
service TaskService{
rpc TaskCreate(TaskRequest) returns(CommonResponse);
rpc TaskUpdate(TaskRequest) returns(CommonResponse);
rpc TaskShow(TaskRequest) returns(TasksDetailResponse);
rpc TaskDelete(TaskRequest) returns(CommonResponse);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
获取所有生成pb.go文件
protoc -I internal/service/pb internal/service/pb/*.proto --go_out=plugins=grpc:.
- 1
1.2 数据库结构定义
- 模型定义
type Task struct {
TaskID uint `gorm:"primarykey"` // 收藏夹id
UserID uint `gorm:"index"` // 用户id
Status int `gorm:"default:0"`
Title string
Content string `gorm:"type:longtext"`
StartTime int64
EndTime int64
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 展示所有的任务
func (*Task) Show (req *service.TaskRequest)(taskList []Task,err error) {
err = DB.Model(Task{}).Where("user_id=?", req.UserID).Find(&taskList).Error
if err != nil {
return taskList, err
}
return taskList, nil
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 创建备忘录
func (*Task) Create (req *service.TaskRequest) error {
task := Task{
UserID: uint(req.UserID),
Title : req.Title,
Content : req.Content,
Status : int(req.Status),
StartTime : int64(req.StartTime),
EndTime : int64(req.EndTime),
}
if err := DB.Create(&task).Error; err != nil {
util.LogrusObj.Error("Insert Task Error:" + err.Error())
return err
}
return nil
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 删除备忘录
func (*Task) Delete(req *service.TaskRequest) error {
err := DB.Where("task_id=?", req.TaskID).Delete(Task{}).Error
return err
}
- 1
- 2
- 3
- 4
- 更新
func (*Task) Update(req *service.TaskRequest) error {
t := Task{}
err := DB.Where("task_id=?", req.TaskID).First(&t).Error
if err != nil {
return err
}
t.Title = req.Title
t.Content = req.Content
t.Status = int(req.Status)
t.StartTime = int64(req.StartTime)
t.EndTime = int64(req.EndTime)
err = DB.Save(&t).Error
return err
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
1.3 接入ETCD
- ETCD服务初始化
etcdAddress := []string{viper.GetString("etcd.address")}
etcdRegister := discovery.NewRegister(etcdAddress, logrus.New())
grpcAddress := viper.GetString("server.grpcAddress")
- 1
- 2
- 3
- 节点接入ETCD
taskNode := discovery.Server{
Name: viper.GetString("server.domain"),
Addr: grpcAddress,
}
server := grpc.NewServer()
- 1
- 2
- 3
- 4
- 5
- 服务注册节点
service.RegisterTaskServiceServer(server, handler.NewTaskService())
lis, err := net.Listen("tcp", grpcAddress)
if err != nil {
panic(err)
}
if _, err := etcdRegister.Register(taskNode, 10); err != nil {
panic(fmt.Sprintf("start server failed, err: %v", err))
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
2. 网关接入
2.1 服务接入
- 获取ETCD的服务
taskConn, _ := grpc.Dial("127.0.0.1:10002", opts...)
taskService := service.NewTaskServiceClient(taskConn)
- 1
- 2
- 路由注入
authed := v1.Group("/")
authed.Use(middleware.JWT())
{
// 任务模块
authed.GET("task", handler.GetTaskList)
authed.POST("task", handler.CreateTask)
authed.PUT("task", handler.UpdateTask)
authed.DELETE("task", handler.DeleteTask)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
将服务存放在gin.Keys中
func InitMiddleware(service []interface{}) gin.HandlerFunc {
return func(context *gin.Context) {
// 将实例存在gin.Keys中
context.Keys = make(map[string]interface{})
context.Keys["user"] = service[0]
context.Keys["task"] = service[1]
context.Next()
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
2.2 controller
- 获取token,获取是哪个用户
claim, _ := util.ParseToken(ginCtx.GetHeader("Authorization"))
- 1
- 获取task服务
TaskService := ginCtx.Keys["task"].(service.TaskServiceClient)
- 1
- 调用服务
TaskResp, err := TaskService.TaskShow(context.Background(), &fReq)
- 1
- 完整代码
func GetTaskList(ginCtx *gin.Context) {
var fReq service.TaskRequest
PanicIfTaskError(ginCtx.Bind(&fReq))
claim, _ := util.ParseToken(ginCtx.GetHeader("Authorization"))
fReq.UserID = uint32(claim.UserID)
TaskService := ginCtx.Keys["task"].(service.TaskServiceClient)
TaskResp, err := TaskService.TaskShow(context.Background(), &fReq)
PanicIfTaskError(err)
r := res.Response{
Data: TaskResp,
Status: uint(TaskResp.Code),
Msg: e.GetMsg(uint(TaskResp.Code)),
}
ginCtx.JSON(http.StatusOK, r)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
3. 测试返回
文章来源: blog.csdn.net,作者:小生凡一,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/weixin_45304503/article/details/125348318
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)