首页 > 其他分享 >go-zero 微服务框架集成 gorm 实操

go-zero 微服务框架集成 gorm 实操

时间:2024-08-03 15:05:54浏览次数:9  
标签:string err json yaml zero 实操 go gorm mysqlConf

目录
作为服务,肯定要和数据库交互的,所以在 go-zero 框架里集成 数据库 的操作是必不可少的,今天看看 go-zero 的 rpc 应用如何集成 gorm 框架。

总体的思路分这几步:

  • 定义你的配置项结构体
  • 定义你的配置
  • 添加到 svcContext
  • 实现你的模型
  • 具体业务逻辑的应用

1.config 的结构体

package config

import (
	"github.com/zeromicro/go-zero/zrpc"
)

type Config struct {
	zrpc.RpcServerConf
	MySQLConf MySQLConf
}

// Mysql config
type MySQLConf struct {
	Host 					  string 		`json:"" yaml:"Host"`
	Port 					  int64 		`json:"" yaml:"Port"`
	User 					  string 		`json:"" yaml:"User"`
	Password				  string 		`json:"" yaml:"Password"`
	Database 				  string 		`json:"" yaml:"Database"`
	CharSet 			 	  string 		`json:"" yaml:"CharSet"`
	TimeZone 				  string 		`json:"" yaml:"TimeZone"`
	ParseTime 				  bool 			`json:"" yaml:"ParseTime"`
	Enable                    bool          `json:"" yaml:"Enable"`					   // use mysql or not

	//DefaultStringSize         uint          `json:"" yaml:"DefaultStringSize"`         // string 类型字段的默认长度
	AutoMigrate 			  bool 			`json:"" yaml:"AutoMigrate"`
	//DisableDatetimePrecision  bool          `json:"" yaml:"DisableDatetimePrecision"`  // 禁用 datetime 精度
	//SkipInitializeWithVersion bool          `json:"" yaml:"SkipInitializeWithVersion"` // 根据当前 MySQL 版本自动配置
	//
	//SlowSql                   time.Duration `json:"" yaml:"SlowSql"`                   //慢SQL
	//LogLevel                  string        `json:"" yaml:"LogLevel"`                  // 日志记录级别
	//IgnoreRecordNotFoundError bool          `json:"" yaml:"IgnoreRecordNotFoundError"` // 是否忽略ErrRecordNotFound(未查到记录错误)

	Gorm                      GormConf          `json:"" yaml:"Gorm"`
}

// gorm config
type GormConf struct {
	//SkipDefaultTx   bool   `json:"" yaml:"SkipDefaultTx"`                            //是否跳过默认事务
	//CoverLogger     bool   `json:"" yaml:"CoverLogger"`                              //是否覆盖默认logger
	//PreparedStmt    bool   `json:"" yaml:"PreparedStmt"`                              // 设置SQL缓存
	//CloseForeignKey bool   `json:"" yaml:"CloseForeignKey"` 						// 禁用外键约束
	SingularTable   bool   `json:"" yaml:"SingularTable"`                            //是否使用单数表名(默认复数),启用后,User结构体表将是user
	TablePrefix     string `json:"" yaml:"TablePrefix"`                              // 表前缀
	MaxOpenConns int `json:"" yaml:"MaxOpenConns"`
	MaxIdleConns int `json:"" yaml:"MaxIdleConns"`
	ConnMaxLifetime int `json:"" yaml:"ConnMaxLifetime"`
}

2.配置文件声明

MySQLConf:
  Enable: true
  User: user1
  Password: user1
  Host: 172.30.5.240
  Port: 3306
  Database: zero
  CharSet: utf8
  ParseTime: true
  TimeZOne: Local
  AutoMigrate: true
  Gorm:
    TablePrefix: zero_
    SingularTable: true
    MaxOpenConns: 100
    MaxIdleConns: 5
    ConnMaxLifetime: 600

3.添加 svcContext

package svc

import (
	"fmt"
	"time"

	"userrpcv1/internal/config"
	"userrpcv1/internal/models"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

type ServiceContext struct {
	Config config.Config

	// claim ur redis client in here
	//RedisClient *zeroRds.Redis

	// claim ur mysql here
	DBEngine *gorm.DB
}

func NewServiceContext(c config.Config) *ServiceContext {
	// redis
	//conf := c.Redis
	//redisClient := zeroRds.MustNewRedis(conf.RedisConf)

	// mysql
	mysqlConf := c.MySQLConf
	var db *gorm.DB
	var err error
	if mysqlConf.Enable {
		db, err = creteDbClient(mysqlConf)
		if err != nil {
			db = nil
		}
	}

	return &ServiceContext{
		Config: c,

		//RedisClient: redisClient,

		DBEngine: db,
	}
}

func creteDbClient(mysqlConf config.MySQLConf) (*gorm.DB, error) {
	datasource := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=%t&loc=%s",
		mysqlConf.User,
		mysqlConf.Password,
		mysqlConf.Host,
		mysqlConf.Port,
		mysqlConf.Database,
		mysqlConf.CharSet,
		mysqlConf.ParseTime,
		mysqlConf.TimeZone)
	db, err := gorm.Open(mysql.Open(datasource), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix: mysqlConf.Gorm.TablePrefix, // such as: prefix_tableName
			SingularTable: mysqlConf.Gorm.SingularTable, // such as zero_user, not zero_users
		},
	})
	if err != nil {
		logx.Errorf("create mysql db failed, err: %v", err)
		return nil, err
	}

	// auto sync table structure, no need to create table
	err = db.AutoMigrate(&models.User{})
	if err != nil {
		logx.Errorf("automigrate table failed, err: %v", err)
	}

	logx.Info("init mysql client instance success.")

	sqlDB, err := db.DB()
	if err != nil {
		logx.Errorf("mysql set connection pool failed, err: %v.", err)
		return nil, err
	}
	sqlDB.SetMaxOpenConns(mysqlConf.Gorm.MaxOpenConns)
	sqlDB.SetMaxIdleConns(mysqlConf.Gorm.MaxIdleConns)
	sqlDB.SetConnMaxLifetime(time.Duration(mysqlConf.Gorm.ConnMaxLifetime) * time.Second)

	return db, nil
}

4.定义你的相关表或者模型

models/user.go

package models

import "time"

// base model
type BaseModel struct {
	ID        int64     `json:"id" gorm:"column:id;autoIncrement;primaryKey"`
	CreatedAt time.Time `json:"createdAt" gorm:"column:createdAt"`
	UpdatedAt time.Time `json:"updatedAt" gorm:"column:updatedAt"`
	DeletedAt time.Time `json:"-" gorm:"column:deletedAt"`
}

// user table
type User struct {
	BaseModel
	Username string `json:"username" gorm:"column:username;type:varchar(20);unique:un_username;not null;comment:用户名"`
	NickName string `json:"nickName" gorm:"column:nickname;type:varchar(20);not null;default:'-';comment:昵称"`
	Phone    int    `json:"phone" gorm:"column:phone;type:int;unique:un_phone;comment:手机号"`
	Password string `json:"-" gorm:"column:password;type:varchar(40);comment:密码"`
	Status   int8   `json:"status" gorm:"column:status;size:4;default:1;comment:状态 1:正常 2:白名单 3:黑名单"`
	IsAdmin  bool   `json:"is_admin" gorm:"column:is_admin;default:false"`
}

// userProfile table
type UserInfo struct {
	BaseModel
	Address string `json:"address" gorm:"column:address;type:varchar(100)"`
	Uid     uint   `json:"uid" gorm:"column:uid;comment:用户id"`
}

接着你就可以拿到 db 在你的业务逻辑进行操作了。

注意这里需要先创建相关的数据库。

标签:string,err,json,yaml,zero,实操,go,gorm,mysqlConf
From: https://www.cnblogs.com/davis12/p/18340551

相关文章

  • 第一个Django工程创建及运行
    认识DjangoDjango是一个高级PythonWeb框架,它鼓励快速开发和简洁、实用的设计。它由经验丰富的开发人员构建,解决了Web开发的大部分麻烦,因此您可以专注于编写应用程序,而无需重新发明轮子。它是免费和开源的。快得离谱。Django旨在帮助开发人员尽快将应用程序从概念到......
  • 计算机毕业设计django+vue博物馆信息系统【开题+论文+程序】
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景随着科技的飞速发展和人们对文化生活的追求日益提升,博物馆作为连接过去与未来的桥梁,其信息化建设已成为不可逆转的趋势。传统的博物馆管理......
  • GO语言 4 收集器
    劳苦功高的数组声明数组并访问其元素以下数组不多不少正好包含8个元素varplanets[8]string同一个数组中的每个元素都具有相同的类型,比如以上代码就是由8个字符串组成,简称字符串数组。数组的长度可以通过内置的len函数确定。在声明数组时,未被赋值的元素将包含......
  • 02 Go语言操作MySQL基础教程_20240729 课程笔记
    概述如果您没有Golang的基础,应该学习如下前置课程。Golang零基础入门Golang面向对象编程GoWeb基础Go语言开发RESTAPI接口_20240728基础不好的同学每节课的代码最好配合视频进行阅读和学习,如果基础比较扎实,则阅读本教程巩固一下相关知识点即可,遇到不会的知识点再看视频......
  • go-zero 使用 redis 作为 cache 的 2 种姿势
    在go-zero框架内,如在rpc的应用service中,其内部已经预置了redis的应用,所以我们只需要在配置中加入相关字段即可,另外,在svcContext声明redisclient后即可在具体的业务逻辑处理中应用。但这里有个问题,如我用的是go-zero1.5.0版本,从源码分析来看,redis的连接并没用到......
  • EGO-Swarm仿真环境搭建
    EGO-Swarm仿真环境搭建参考教程:https://github.com/ZJU-FAST-Lab/ego-planner-swarmEGO-Swarm是一种分散的异步系统解决方案,用于仅使用机载资源在未知的障碍物丰富的场景中进行多机器人自主导航。1.查看系统环境要运行本仿真程序,需要保证当前环境为ubuntu18.04+ros-melodic......
  • 奥运会Ⅰ--Google大模型 - 效率的伟大胜利
    不惜一切代价正如我们多次提到的,LLM最看重的是规模。这是因为随着参数数量的增加,这些模型会开发出新功能。因此,这些模型的每一代新模型通常都比之前的模型大得多,其中GPT-4的大小是GPT-3的十倍,而据传GPT-5比GPT-4大30倍(如果我们使用微软首席技术官KevinScott对......
  • 在 Go 中,`fmt.Printf` 常用的 `%` 占位符类型
    在Go中,fmt.Printf常用的%占位符类型如下:%v:值的默认格式表示。%+v:结构体字段名和值的格式表示。%#v:Go语法表示的值。%T:值的类型。%%:百分号字面量。对于特定类型:%d:整数(十进制)。%b:整数(二进制)。%o:整数(八进制)。%x,%X:整数(十六进制)。%f:浮点数。%e,%E:科学......
  • Google 推出 Gemma 2 2B 端侧模型;Github 新服务帮助开发者选择 AI 模型 丨 RTE 开发者
       开发者朋友们大家好: 这里是「RTE开发者日报」,每天和大家一起看新闻、聊八卦。我们的社区编辑团队会整理分享RTE(Real-TimeEngagement)领域内「有话题的新闻」、「有态度的观点」、「有意思的数据」、「有思考的文章」、「有看点的会议」,但内容仅代表编辑的个人观点......
  • 如何架构优秀的Go后端REST API服务
    如何架构优秀的Go后端RESTAPI服务原创 K8sCat 源自开发者 2024年07月01日18:12 广东源自开发者专注于提供关于Go语言的实用教程、案例分析、最新趋势,以及云原生技术的深度解析和实践经验分享。283篇原创内容公众号REST(RepresentationalStateTransfe......