init project
This commit is contained in:
1 parent
d63cc8d9f5
commit
ee07869839
39 files changed
+1560
-622
No files matched your search
+100
-54
@@ -1,74 +1,120 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/go-redis/redis"
|
||||
|
||||
xormxlog "git.xiaotuo.co/pkg/go-plugins/xormx/log"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"xorm.io/xorm"
|
||||
mysqldriver "github.com/go-sql-driver/mysql"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
gormlog "gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
var (
|
||||
DefaultMaxOpenConn = 10
|
||||
DefaultMaxIdleConn = 5
|
||||
DefaultConnMaxLifetime = 1
|
||||
)
|
||||
var ErrDatabaseDisabled = errors.New("mysql is disabled")
|
||||
|
||||
type Storage struct {
|
||||
engine *xorm.Engine
|
||||
db *gorm.DB
|
||||
redis *redis.Client
|
||||
}
|
||||
|
||||
func NewStorage(conf Config) (*Storage, error) {
|
||||
rs := redis.NewClient(&redis.Options{
|
||||
Addr: conf.Redis.Addr,
|
||||
Password: conf.Redis.Auth,
|
||||
DB: conf.Redis.DB,
|
||||
})
|
||||
if _, err := rs.Ping().Result(); err != nil {
|
||||
return nil, fmt.Errorf("redis.Ping: %v", err)
|
||||
st := &Storage{}
|
||||
if conf.Mysql.Enabled {
|
||||
driverConfig, err := mysqldriver.ParseDSN(conf.Mysql.DSN)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid mysql DSN")
|
||||
}
|
||||
driverConfig.ParseTime = true
|
||||
driverConfig.Timeout = conf.Mysql.ConnectTimeout
|
||||
driverConfig.ReadTimeout = conf.Mysql.ConnectTimeout
|
||||
driverConfig.WriteTimeout = conf.Mysql.ConnectTimeout
|
||||
if driverConfig.Params == nil {
|
||||
driverConfig.Params = map[string]string{}
|
||||
}
|
||||
driverConfig.Params["charset"] = "utf8mb4"
|
||||
sqlLogger := gormlog.Default.LogMode(gormlog.Silent)
|
||||
if conf.Mysql.ShowSQL {
|
||||
sqlLogger = gormlog.New(logWriter{}, gormlog.Config{
|
||||
SlowThreshold: time.Second,
|
||||
LogLevel: gormlog.Info,
|
||||
IgnoreRecordNotFoundError: true,
|
||||
ParameterizedQueries: false,
|
||||
})
|
||||
}
|
||||
db, err := gorm.Open(mysql.New(mysql.Config{
|
||||
DSN: driverConfig.FormatDSN(),
|
||||
SkipInitializeWithVersion: true,
|
||||
}), &gorm.Config{Logger: sqlLogger, DisableAutomaticPing: true})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("initialize mysql failed: %w", err)
|
||||
}
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get mysql connection pool: %w", err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(conf.Mysql.MaxOpenConn)
|
||||
sqlDB.SetMaxIdleConns(conf.Mysql.MaxIdleConn)
|
||||
sqlDB.SetConnMaxLifetime(conf.Mysql.ConnMaxLifetime)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), conf.Mysql.ConnectTimeout)
|
||||
err = sqlDB.PingContext(ctx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
_ = sqlDB.Close()
|
||||
return nil, fmt.Errorf("connect mysql failed: %w", err)
|
||||
}
|
||||
st.db = db
|
||||
}
|
||||
log.Infof("redis addr: %s, db: %d", conf.Redis.Addr, conf.Redis.DB)
|
||||
|
||||
if len(conf.Mysql.DB) == 0 {
|
||||
return nil, errors.New("db init failed: 数据库配置项为空")
|
||||
if conf.Redis.Enabled {
|
||||
st.redis = redis.NewClient(&redis.Options{
|
||||
Addr: conf.Redis.Addr,
|
||||
Password: conf.Redis.Password,
|
||||
DB: conf.Redis.DB,
|
||||
DialTimeout: conf.Redis.ConnectTimeout,
|
||||
ReadTimeout: conf.Redis.ConnectTimeout,
|
||||
WriteTimeout: conf.Redis.ConnectTimeout,
|
||||
ContextTimeoutEnabled: true,
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), conf.Redis.ConnectTimeout)
|
||||
err := st.redis.Ping(ctx).Err()
|
||||
cancel()
|
||||
if err != nil {
|
||||
_ = st.Close()
|
||||
return nil, errors.New("connect redis failed")
|
||||
}
|
||||
}
|
||||
if conf.Mysql.MaxIdleConn == 0 {
|
||||
conf.Mysql.MaxIdleConn = DefaultMaxIdleConn
|
||||
}
|
||||
if conf.Mysql.MaxOpenConn == 0 {
|
||||
conf.Mysql.MaxOpenConn = DefaultMaxOpenConn
|
||||
}
|
||||
if conf.Mysql.ConnMaxLifetime == 0 {
|
||||
conf.Mysql.ConnMaxLifetime = DefaultConnMaxLifetime
|
||||
}
|
||||
engine, err := xorm.NewEngine("mysql", conf.Mysql.DB)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("NewEngine: %v", err)
|
||||
}
|
||||
log.Infof("mysql addr: %s", xormxlog.SafeAddr(conf.Mysql.DB))
|
||||
|
||||
engine.SetMaxOpenConns(conf.Mysql.MaxOpenConn)
|
||||
engine.SetMaxIdleConns(conf.Mysql.MaxIdleConn)
|
||||
engine.SetConnMaxLifetime(time.Hour * time.Duration(conf.Mysql.ConnMaxLifetime))
|
||||
|
||||
if conf.Mysql.ShowSQL {
|
||||
engine.SetLogger(xormxlog.NewXormxLogger())
|
||||
engine.ShowSQL(true)
|
||||
}
|
||||
// redisLog := conf.Mysql.ShowSQL
|
||||
|
||||
return &Storage{
|
||||
engine: engine,
|
||||
}, nil
|
||||
return st, nil
|
||||
}
|
||||
|
||||
func (s *Storage) NewSession() *xorm.Session {
|
||||
return s.engine.NewSession()
|
||||
func (st *Storage) DB() *gorm.DB {
|
||||
return st.db
|
||||
}
|
||||
|
||||
type TransactionClosure func(tx *xorm.Session) error
|
||||
func (st *Storage) Redis() *redis.Client {
|
||||
return st.redis
|
||||
}
|
||||
|
||||
func (st *Storage) Transaction(ctx context.Context, closure func(tx *gorm.DB) error) error {
|
||||
if st.db == nil {
|
||||
return ErrDatabaseDisabled
|
||||
}
|
||||
return st.db.WithContext(ctx).Transaction(closure)
|
||||
}
|
||||
|
||||
func (st *Storage) Close() error {
|
||||
var result error
|
||||
if st.redis != nil {
|
||||
result = errors.Join(result, st.redis.Close())
|
||||
}
|
||||
if st.db != nil {
|
||||
sqlDB, err := st.db.DB()
|
||||
if err != nil {
|
||||
result = errors.Join(result, err)
|
||||
} else {
|
||||
result = errors.Join(result, sqlDB.Close())
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
Reference in new issue
Block a user