Documentation ¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetRedisConn ¶
GetRedisConn 用来获取一个 redis 连接实例 使用之前应该确保连接池已经被初始化了
func InitDBSetting ¶
func InitDBSetting(set interface{}) error
初始化数据库连接.
对于 set, 可以传入一个任意类型的 struct, 但是需要保证 set 里包含 初始化连接所必须的参数,并且使用正确的 json 标签,具体参数和标签可以 参考 DBConnector, 其中 check 标签标记为 not null 的是必须参数,如:
conn := DBConn{ Engine: "mysql", DBName: "test", User: "test", Password: "123456", Host: "127.0.0.1", Port: 3306, MIdleConn: idle, MOpenConn: open, MLifetime: time.Second * 3, LogMode: false, } err := InitDBSetting(&conn)
若初始化成功,则返回值 error 应该为 nil。
初始化成功后,可以调用 GetDB 获取具体的 *gorm.DB 对象.
func InitRedisPool ¶
func InitRedisPool(setting interface{}) error
InitRedisPool 用来初始化一个 Redis 连接池 对象 你需要传递一个包含上面 RedisConn 结构体中字段的对象 (无所谓类型,只需要 json 标签与类型对应即可,其中 check 标签标记为 not null 的是必须字段)在应用程序中 连接池对象只需要初始化一遍即可使用 GetRedisConn 获取 连接实例去执行了,多次调用也不会多次实例化
func UseTransaction ¶
将 def 以一个事务的方式执行。
def 是执行一组 ORM 语句的函数,他应该满足以下条件:
1. 第一个参数是 *gorm.DB 类型,def 中的所有 ORM 操作都应该使用改对象。
2. 返回应该至少有一个是 error 类型的,如果有多个返回值时,error 类型的应该作为最后一个。
函数会返回 def 执行的结果,他以 reflect.Value 切片的形式返回
Example ¶
def := func(db *gorm.DB, res *Table, id uint, name string) (ok bool, err error) { err = db.Select("id = ?, lname = ?", id, name).First(&res).Error if err != nil { return false, err } err = db.Create(&Table{ Name: "p", }).Error if err != nil { return false, err } return true, nil } res := Table{} args := []interface{}{ &gorm.DB{}, &res, uint(83), "13", } resL, err := UseTransaction(def, args) if err != nil { log.Println(err) } fmt.Println(res) if resL[0].Bool() { fmt.Println("insert success") }
Output:
Types ¶
type DBConnector ¶
type DBConnector struct { Engine string `json:"engine" check:"not null"` DBName string `json:"db_name" check:"not null"` User string `json:"user" check:"not null"` Password string `json:"password" check:"not null"` Host string `json:"host" check:"not null"` Port int `json:"port" check:"not null"` MaxIdleConn int `json:"max_idle_conn"` // 最大空闲连接数 MaxOpenConn int `json:"max_open_conn"` // 最大打开连接数 MaxLifetime time.Duration `json:"max_lifetime"` // 连接超时时间 LogMode bool `json:"log_mode"` }
定义建立数据库连接时所需要的值,可以使用任意类型的 struct, 只要 json 标签于此对于即可,对于类似 Engine, User 等必须参数 我们会使用 check.Check 检查,请确保值正确。
func (*DBConnector) NewConnect ¶
func (conn *DBConnector) NewConnect() *gorm.DB
type RedisConn ¶
type RedisConn struct { Host string `json:"host" check:"not null"` Password string `json:"password" check:"not null"` Port int `json:"port" check:"not null"` MIdleConn int `json:"max_idle_conn"` // 最大空闲连接数 MOpenConn int `json:"max_open_conn"` // 最大打开连接数 MLifetime time.Duration `json:"max_lifetime"` // 连接超时时间 }