init project
This commit is contained in:
1 parent
d63cc8d9f5
commit
ee07869839
39 files changed
+1560
-622
No files matched your search
Vendored
+10
-10
@@ -5,8 +5,8 @@ import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"git.xiaotuo.co/micro/skeleton/internal/logger"
|
||||
"github.com/go-redis/redis"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"micro_layout/internal/logger"
|
||||
)
|
||||
|
||||
type BaseCache struct {
|
||||
@@ -15,7 +15,7 @@ type BaseCache struct {
|
||||
}
|
||||
|
||||
func (c *BaseCache) exists(ctx context.Context, key string) (bool, error) {
|
||||
value, err := c.rs.Exists(key).Result()
|
||||
value, err := c.rs.Exists(ctx, key).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
if c.isLog {
|
||||
logger.Debugf(ctx, "redis_exists", "key: %s, not_found", key)
|
||||
@@ -36,7 +36,7 @@ func (c *BaseCache) exists(ctx context.Context, key string) (bool, error) {
|
||||
}
|
||||
|
||||
func (c *BaseCache) get(ctx context.Context, key string) (string, error) {
|
||||
value, err := c.rs.Get(key).Result()
|
||||
value, err := c.rs.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if c.isLog {
|
||||
logger.Errorf(ctx, "redis_get", "key: %s, err: %v", key, err)
|
||||
@@ -50,7 +50,7 @@ func (c *BaseCache) get(ctx context.Context, key string) (string, error) {
|
||||
}
|
||||
|
||||
func (c *BaseCache) set(ctx context.Context, key string, value interface{}, expire time.Duration) (string, error) {
|
||||
result, err := c.rs.Set(key, value, expire).Result()
|
||||
result, err := c.rs.Set(ctx, key, value, expire).Result()
|
||||
if err != nil {
|
||||
if c.isLog {
|
||||
logger.Errorf(ctx, "redis_set", "key: %s, value: %v, err: %v", key, value, err)
|
||||
@@ -64,7 +64,7 @@ func (c *BaseCache) set(ctx context.Context, key string, value interface{}, expi
|
||||
}
|
||||
|
||||
func (c *BaseCache) del(ctx context.Context, key string) (int64, error) {
|
||||
affect, err := c.rs.Del(key).Result()
|
||||
affect, err := c.rs.Del(ctx, key).Result()
|
||||
if err != nil {
|
||||
if c.isLog {
|
||||
logger.Errorf(ctx, "redis_del", "key: %s, err: %v", key, err)
|
||||
@@ -78,7 +78,7 @@ func (c *BaseCache) del(ctx context.Context, key string) (int64, error) {
|
||||
}
|
||||
|
||||
func (c *BaseCache) push(ctx context.Context, key string, values ...interface{}) (int64, error) {
|
||||
affect, err := c.rs.LPush(key, values...).Result()
|
||||
affect, err := c.rs.LPush(ctx, key, values...).Result()
|
||||
if err != nil {
|
||||
if c.isLog {
|
||||
logger.Errorf(ctx, "redis_lpush", "key: %s, err: %v", key, err)
|
||||
@@ -92,7 +92,7 @@ func (c *BaseCache) push(ctx context.Context, key string, values ...interface{})
|
||||
}
|
||||
|
||||
func (c *BaseCache) pop(ctx context.Context, key string) (string, error) {
|
||||
value, err := c.rs.RPop(key).Result()
|
||||
value, err := c.rs.RPop(ctx, key).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
if c.isLog {
|
||||
logger.Tracef(ctx, "redis_rpop", "key: %s null", key)
|
||||
@@ -112,7 +112,7 @@ func (c *BaseCache) pop(ctx context.Context, key string) (string, error) {
|
||||
}
|
||||
|
||||
func (c *BaseCache) length(ctx context.Context, key string) (int64, error) {
|
||||
l, err := c.rs.LLen(key).Result()
|
||||
l, err := c.rs.LLen(ctx, key).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
if c.isLog {
|
||||
logger.Debugf(ctx, "redis_llen", "key: %s null", key)
|
||||
@@ -132,7 +132,7 @@ func (c *BaseCache) length(ctx context.Context, key string) (int64, error) {
|
||||
}
|
||||
|
||||
func (c *BaseCache) lock(ctx context.Context, key, value string, expire time.Duration) (bool, error) {
|
||||
result, err := c.rs.SetNX(key, value, expire).Result()
|
||||
result, err := c.rs.SetNX(ctx, key, value, expire).Result()
|
||||
if err != nil {
|
||||
if c.isLog {
|
||||
logger.Errorf(ctx, "redis_setnx", "key: %s, err: %v", key, err)
|
||||
|
||||
+44
-11
@@ -1,21 +1,54 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
mysqldriver "github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Mysql ConfigMysql `json:"mysql"`
|
||||
Redis ConfigRedis `json:"redis"`
|
||||
Mysql ConfigMysql `mapstructure:"mysql"`
|
||||
Redis ConfigRedis `mapstructure:"redis"`
|
||||
}
|
||||
|
||||
type ConfigMysql struct {
|
||||
DB string `json:"db"`
|
||||
Debug bool `json:"debug"`
|
||||
ShowSQL bool `json:"show_sql"`
|
||||
MaxOpenConn int `json:"max_open_conn"`
|
||||
MaxIdleConn int `json:"max_idle_conn"`
|
||||
ConnMaxLifetime int `json:"conn_max_life_time"`
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
DSN string `mapstructure:"dsn"`
|
||||
ShowSQL bool `mapstructure:"show_sql"`
|
||||
MaxOpenConn int `mapstructure:"max_open_conn"`
|
||||
MaxIdleConn int `mapstructure:"max_idle_conn"`
|
||||
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"`
|
||||
ConnectTimeout time.Duration `mapstructure:"connect_timeout"`
|
||||
}
|
||||
|
||||
type ConfigRedis struct {
|
||||
Addr string `json:"addr"`
|
||||
Auth string `json:"auth"`
|
||||
DB int `json:"db"`
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
Addr string `mapstructure:"addr"`
|
||||
Password string `mapstructure:"password"`
|
||||
DB int `mapstructure:"db"`
|
||||
ConnectTimeout time.Duration `mapstructure:"connect_timeout"`
|
||||
}
|
||||
|
||||
func (cfg Config) Validate() error {
|
||||
if cfg.Mysql.Enabled {
|
||||
mysql := cfg.Mysql
|
||||
if strings.TrimSpace(mysql.DSN) == "" {
|
||||
return errors.New("storage.mysql.dsn is required when mysql is enabled")
|
||||
}
|
||||
if _, err := mysqldriver.ParseDSN(mysql.DSN); err != nil {
|
||||
return errors.New("storage.mysql.dsn is invalid")
|
||||
}
|
||||
if mysql.MaxOpenConn <= 0 || mysql.MaxIdleConn < 0 || mysql.MaxIdleConn > mysql.MaxOpenConn {
|
||||
return errors.New("mysql connection pool requires max_open_conn > 0 and 0 <= max_idle_conn <= max_open_conn")
|
||||
}
|
||||
if mysql.ConnMaxLifetime <= 0 || mysql.ConnectTimeout <= 0 {
|
||||
return errors.New("mysql connection durations must be greater than zero")
|
||||
}
|
||||
}
|
||||
if cfg.Redis.Enabled && (strings.TrimSpace(cfg.Redis.Addr) == "" || cfg.Redis.DB < 0 || cfg.Redis.ConnectTimeout <= 0) {
|
||||
return errors.New("enabled redis requires addr, non-negative db and positive connect_timeout")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package storage
|
||||
|
||||
import log "github.com/sirupsen/logrus"
|
||||
|
||||
type logWriter struct{}
|
||||
|
||||
func (logWriter) Printf(format string, args ...interface{}) {
|
||||
log.Infof(format, args...)
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package model
|
||||
|
||||
import "gorm.io/plugin/soft_delete"
|
||||
|
||||
type BaseModel struct {
|
||||
Id int64 `json:"id" xorm:"pk autoincr 'id'"`
|
||||
CreatedAt int64 `json:"created_at" xorm:"created"`
|
||||
UpdatedAt int64 `json:"updated_at" xorm:"updated"`
|
||||
DeletedAt int64 `json:"deleted_at" xorm:"deleted notnull"`
|
||||
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
CreatedAt int64 `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt int64 `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
DeletedAt soft_delete.DeletedAt `json:"deleted_at" gorm:"softDelete:second;not null;default:0;index"`
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package model
|
||||
|
||||
type User struct {
|
||||
BaseModel
|
||||
Name string `json:"name" gorm:"size:100;not null"`
|
||||
Status string `json:"status" gorm:"size:20;not null"`
|
||||
}
|
||||
+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