重要的参考资料

*** 这里有详细的关于ORM操作的需求

PostgreSQL client and ORM for Go

自己做的练习

go-pg库操作PostgreSQL小结 

package gp_gp_tests

import (
    "github.com/go-pg/pg/v10"
    "time"
)

// DataBase的配置
type DatabaseConfig struct {
    URL                    string `yaml:"url"`
    ConnMaxLifetimeSeconds int    `yaml:"conn_max_lifetime_sec"`
    MaxOpenConns           int    `yaml:"max_open_conns"`
    MinIdleConns           int    `yaml:"min_idle_conns"`
    MaxRetries             int    `yaml:"max_retries"`
}

const defaultDBConnMaxRetries = 5

type DBService struct {
    *pg.DB
}

func InitDBService(dbCfg *DatabaseConfig) (*pg.DB, string, error) {
    // 1: 根据postgre的链接信息,生成一个 Options 对象
    opt, err := pg.ParseURL(dbCfg.URL)
    if err != nil {
        return nil, "", err
    }

    // 2:这里给 Options对象设置 链接、链接池 相关的参数~~~最长链接时间、最小空闲链接数、链接池最大链数(即链接池的大小)、最大重试次数~
    // 最大链接时间
    opt.MaxConnAge = time.Second * time.Duration(dbCfg.ConnMaxLifetimeSeconds)
    // 最小的空闲链接数
    opt.MinIdleConns = dbCfg.MinIdleConns
    // 链接池的最大连接数
    opt.PoolSize = dbCfg.MaxOpenConns
    // 最大retry次数
    if dbCfg.MaxRetries == 0 {
        opt.MaxRetries = defaultDBConnMaxRetries
    } else {
        opt.MaxRetries = dbCfg.MaxRetries
    }

    // 3: 通过 Options 对象生成DB对象~最终业务代码中用的是DB对象,里面有一个 newConnPool 方法用来设置链接池的~
    db := pg.Connect(opt)
    // 获取 version 信息
    var dbVersion string
    _, err = db.QueryOne(pg.Scan(&dbVersion), "select version()")
    if err != nil {
        return nil, "", err
    }
    return db, dbVersion, nil
}
init_db.go

相关文章:

  • 2021-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-02
猜你喜欢
  • 2021-08-25
  • 2021-09-05
  • 2021-11-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-06
相关资源
相似解决方案