配置数据库连接
- 如何使用gorm连接数据库
db, err := gorm.Open("mysql", "root:mysql@tcp(127.0.0.1:3306)/web?charset=utf8&parseTime=True&loc=Local")
defer db.Close()
- 优化数据库连接
通过go-zero自带的配置文件实例获取数据库的配置信息,在app/auth/api/etc/auth-api.yml中添加mysql信息如下
Mysql:
Username: root
Password: mysql
Host: 127.0.0.1
Port: "3308"
Database: "yoolib"
Charset: "utf8mb4"
ParseTime: "false"
Loc: "Local"
TablePrefix: ""
SingularTable: true
PrepareStmt: true
ConnMaxLifetime: 300
MaxIdleConn: 30
ConnMaxIdleTime: 200
MaxOpenConn: 300
IgnoreRecordNotFoundError: false
在app/auth/api/internal/config中添加mysql配置信息
package config
import (
"app/tools/mysql"
"github.com/zeromicro/go-zero/rest"
)
type Config struct {
rest.RestConf
Mysql mysql.Config
}
在app/tools/mysql/工具目录下创建mysql.go
package mysql
import "C"
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
// Config 数据库配置信息
type Config struct {
Username string // 用户名
Password string // 密码
Host string // 链接地址
Port string // 端口
Database string // 数据库名
Charset string // 字符集
ParseTime string // 是否解析时间
Loc string // 时区默认 Local
TablePrefix string // 表前缀
SingularTable bool // 是否使用单数表名 true 是 false 否
PrepareStmt bool // 在执行任何 SQL 时都会创建一个 prepared statement 并将其缓存,以提高后续的效率
ConnMaxLifetime int // 设置了连接可复用的最大时间
MaxIdleConn int // 连接池里面的连接最大存活时长(秒)
ConnMaxIdleTime int //连接池里面的连接最大空闲时长(秒)
MaxOpenConn int // 设置打开数据库连接的最大数量
IgnoreRecordNotFoundError bool // 忽略ErrRecordNotFound(记录未找到)错误
}
// 获取数据库连接实例
func GetDB(c Config) (DB *gorm.DB) {
var err error
// 生成mysql的配置信息
mysqlConfig := mysql.Config{
DSN: fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=%s&loc=%s",
c.Username, c.Password, c.Host, c.Port, c.Database, c.Charset, c.ParseTime, c.Loc),
}
DB, err = gorm.Open(mysql.New(mysqlConfig), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
TablePrefix: c.TablePrefix, // 表名前缀,`User` 的表名应该是 `t_users`
SingularTable: c.SingularTable, // 使用单数表名,启用该选项,此时,`User` 的表名应该是 `t_user`
},
})
if err != nil {
panic(err.Error())
}
return
}
- 集成mysql实例
掌握了怎么连接数据库之后,我们就需要在go-zero中将mysql实例集成进去
根据官方文档,在api/internal/svc/servicecontext.go中声明即可
# servicecontext.go
package svc
import (
"app/auth/api/internal/config"
"app/tools/mysql"
"gorm.io/gorm"
)
type ServiceContext struct {
Config config.Config
Mysql *gorm.DB # 新增数据库
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
Mysql: mysql.GetDB(c.Mysql),
}
}
- 这样数据库就配置好了,接下来我们直接开始编写接口验证一下数据库