db

package
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 11 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrDBAlreadyInitialized = errors.New("db: mysql has already been initialized, call Close() first")

ErrDBAlreadyInitialized 表示 MySQL 单例已经初始化,调用方需要先 Close() 再重新初始化.

Functions

func Close added in v0.1.3

func Close() error

Close 关闭 MySQL 与 Redis 连接,返回聚合后的错误

func CloseRedis added in v0.1.3

func CloseRedis() error

CloseRedis 关闭共享 Redis 客户端并重置单例,便于重新初始化. 供持有同一客户端的组件(如 util.Cache)释放连接时使用。 未初始化时调用是安全的,会返回 nil.

func GetDB

func GetDB() *gorm.DB

GetDB 返回单例 *gorm.DB

func GetRedis

func GetRedis() *redis.Client

GetRedis 返回单例 Redis 客户端

func InitMySQL

func InitMySQL(opts *MySQLOptions) (*gorm.DB, error)

InitMySQL 使用给定的选项创建一个新的 gorm 数据库实例. 初始化成功后复用该实例;失败时不会缓存错误,允许调用方重试. 若单例已存在则返回 ErrDBAlreadyInitialized,需要通过 Close() 关闭后再重新初始化.

func InitRedis

func InitRedis(opts *RedisOptions) (*redis.Client, error)

InitRedis 初始化 Redis 连接. 初始化成功后复用该实例;失败时不会缓存错误,允许调用方重试. CloseRedis 之后可以再次调用 InitRedis 重新建立连接.

Types

type MySQLOptions

type MySQLOptions struct {
	Host                  string
	Username              string
	Password              string
	Database              string
	MaxIdleConnections    int
	MaxOpenConnections    int
	MaxConnectionLifeTime time.Duration
	LogLevel              int
}

MySQLOptions 定义 MySQL 数据库的选项.

func (*MySQLOptions) DSN

func (o *MySQLOptions) DSN() (string, error)

DSN 从 MySQLOptions 返回 DSN. 显式设置读写/连接超时,避免下游异常时 goroutine 长时间阻塞; loc 固定为 UTC,时间统一按 UTC 存储,展示时再转换为本地时区.

转义/校验说明(go-sql-driver/mysql 的 DSN 不支持对用户名、密码转义):

  • database 通过 url.PathEscape 转义,因此可以包含 '/'、'?'、'&'、'%' 等字符;
  • username 拒绝 ':'(第一处 ':' 会被驱动解析为密码分隔符)和控制字符;
  • password 保留原样,驱动从 DSN 末尾向前查找最后一个 '@' 和 '/',因此密码中的 ':'、'@'、'/'、'?' 不会破坏解析;但仍拒绝换行等控制字符;
  • host 必须非空且不能包含控制字符或空白(net 地址位于 tcp(...) 中).

type RedisOptions

type RedisOptions struct {
	Addr         string        // "127.0.0.1:6379"
	Password     string        // 密码
	DB           int           // 数据库
	PoolSize     int           // 连接池大小
	MinIdleConns int           // 最小空闲连接数
	DialTimeout  time.Duration // 连接超时
	ReadTimeout  time.Duration // 读超时
	WriteTimeout time.Duration // 写超时
}

RedisOptions 定义 Redis 连接选项

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL