init project

This commit is contained in:
admin committed 2025-12-05 17:23:29 +08:00
commit d63cc8d9f5
33 files changed
+1529

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
package storage
import (
"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"
)
var (
DefaultMaxOpenConn = 10
DefaultMaxIdleConn = 5
DefaultConnMaxLifetime = 1
)
type Storage struct {
engine *xorm.Engine
}
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)
}
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.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
}
func (s *Storage) NewSession() *xorm.Session {
return s.engine.NewSession()
}
type TransactionClosure func(tx *xorm.Session) error