sqlx: add sqlx db initial logic

pull/351/head
Michael Li 2 years ago
parent aa7a0be729
commit 1ce877fb59
No known key found for this signature in database

@ -122,7 +122,6 @@ func Initialize(suite []string, noDefault bool) {
} }
setupLogger() setupLogger()
setupDBEngine()
} }
func GetOssDomain() string { func GetOssDomain() string {

@ -0,0 +1,27 @@
// Copyright 2023 ROC. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package conf
import (
"sync"
"github.com/go-redis/redis/v8"
)
var (
_redisClient *redis.Client
_onceRedis sync.Once
)
func MustRedis() *redis.Client {
_onceRedis.Do(func() {
_redisClient = redis.NewClient(&redis.Options{
Addr: redisSetting.Host,
Password: redisSetting.Password,
DB: redisSetting.DB,
})
})
return _redisClient
}

@ -18,8 +18,9 @@ const (
sqlite3InCgoEnabled = true sqlite3InCgoEnabled = true
) )
func OpenSqlite3() (*sql.DB, error) { func OpenSqlite3() (string, *sql.DB, error) {
return sql.Open("sqlite3", Sqlite3Setting.Dsn("sqlite3")) db, err := sql.Open("sqlite3", Sqlite3Setting.Dsn("sqlite3"))
return "sqlite3", db, err
} }
func gormOpenSqlite3(opts ...gorm.Option) (*gorm.DB, error) { func gormOpenSqlite3(opts ...gorm.Option) (*gorm.DB, error) {

@ -9,7 +9,6 @@ import (
"time" "time"
"github.com/alimy/cfg" "github.com/alimy/cfg"
"github.com/go-redis/redis/v8"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"gorm.io/driver/mysql" "gorm.io/driver/mysql"
"gorm.io/driver/postgres" "gorm.io/driver/postgres"
@ -20,8 +19,6 @@ import (
) )
var ( var (
Redis *redis.Client
_gormdb *gorm.DB _gormdb *gorm.DB
_onceGorm sync.Once _onceGorm sync.Once
) )
@ -29,14 +26,14 @@ var (
func MustGormDB() *gorm.DB { func MustGormDB() *gorm.DB {
_onceGorm.Do(func() { _onceGorm.Do(func() {
var err error var err error
if _gormdb, err = newDBEngine(); err != nil { if _gormdb, err = newGormDB(); err != nil {
logrus.Fatalf("new gorm db failed: %s", err) logrus.Fatalf("new gorm db failed: %s", err)
} }
}) })
return _gormdb return _gormdb
} }
func newDBEngine() (*gorm.DB, error) { func newGormDB() (*gorm.DB, error) {
newLogger := logger.New( newLogger := logger.New(
logrus.StandardLogger(), // io writer日志输出的目标前缀和日志包含的内容 logrus.StandardLogger(), // io writer日志输出的目标前缀和日志包含的内容
logger.Config{ logger.Config{
@ -85,11 +82,3 @@ func newDBEngine() (*gorm.DB, error) {
return db, err return db, err
} }
func setupDBEngine() {
Redis = redis.NewClient(&redis.Options{
Addr: redisSetting.Host,
Password: redisSetting.Password,
DB: redisSetting.DB,
})
}

@ -19,8 +19,9 @@ const (
sqlite3InCgoEnabled = false sqlite3InCgoEnabled = false
) )
func OpenSqlite3() (*sql.DB, error) { func OpenSqlite3() (string, *sql.DB, error) {
return sql.Open("sqlite", Sqlite3Setting.Dsn("sqlite")) db, err := sql.Open("sqlite", Sqlite3Setting.Dsn("sqlite"))
return "sqlite", db, err
} }
func gormOpenSqlite3(opts ...gorm.Option) (*gorm.DB, error) { func gormOpenSqlite3(opts ...gorm.Option) (*gorm.DB, error) {

@ -5,9 +5,12 @@
package conf package conf
import ( import (
"database/sql"
"sync" "sync"
"github.com/alimy/cfg"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/sirupsen/logrus"
) )
var ( var (
@ -17,7 +20,28 @@ var (
func MustSqlxDB() *sqlx.DB { func MustSqlxDB() *sqlx.DB {
_onceSqlx.Do(func() { _onceSqlx.Do(func() {
// TODO: init sqlx.DB var err error
if _sqlxdb, err = newSqlxDB(); err != nil {
logrus.Fatalf("new sqlx db failed: %s", err)
}
}) })
return _sqlxdb return _sqlxdb
} }
func newSqlxDB() (db *sqlx.DB, err error) {
if cfg.If("MySQL") {
db, err = sqlx.Open("mysql", MysqlSetting.Dsn())
} else if cfg.If("PostgreSQL") || cfg.If("Postgres") {
db, err = sqlx.Open("postgres", PostgresSetting.Dsn())
} else if cfg.If("Sqlite3") {
var (
driver string
sqldb *sql.DB
)
driver, sqldb, err = OpenSqlite3()
db = sqlx.NewDb(sqldb, driver)
} else {
db, err = sqlx.Open("mysql", MysqlSetting.Dsn())
}
return
}

@ -44,7 +44,7 @@ func Run() {
dbName = (*conf.PostgresSetting)["DBName"] dbName = (*conf.PostgresSetting)["DBName"]
db, err = sql.Open("postgres", conf.PostgresSetting.Dsn()) db, err = sql.Open("postgres", conf.PostgresSetting.Dsn())
} else if cfg.If("Sqlite3") { } else if cfg.If("Sqlite3") {
db, err = conf.OpenSqlite3() _, db, err = conf.OpenSqlite3()
} else { } else {
dbName = conf.MysqlSetting.DBName dbName = conf.MysqlSetting.DBName
db, err = sql.Open("mysql", conf.MysqlSetting.Dsn()) db, err = sql.Open("mysql", conf.MysqlSetting.Dsn())

@ -6,6 +6,8 @@ package broker
import ( import (
"github.com/alimy/cfg" "github.com/alimy/cfg"
"github.com/go-redis/redis/v8"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/internal/dao" "github.com/rocboss/paopao-ce/internal/dao"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@ -15,6 +17,7 @@ var (
ds core.DataService ds core.DataService
ts core.TweetSearchService ts core.TweetSearchService
oss core.ObjectStorageService oss core.ObjectStorageService
redisClient *redis.Client
DisablePhoneVerify bool DisablePhoneVerify bool
) )
@ -22,6 +25,7 @@ func Initialize() {
ds = dao.DataService() ds = dao.DataService()
ts = dao.TweetSearchService() ts = dao.TweetSearchService()
oss = dao.ObjectStorageService() oss = dao.ObjectStorageService()
redisClient = conf.MustRedis()
DisablePhoneVerify = !cfg.If("Sms") DisablePhoneVerify = !cfg.If("Sms")
} }

@ -9,7 +9,6 @@ import (
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/convert"
"github.com/rocboss/paopao-ce/pkg/errcode" "github.com/rocboss/paopao-ce/pkg/errcode"
@ -31,7 +30,7 @@ func CreateWhisper(c *gin.Context, msg *core.Message) (*core.Message, error) {
whisperKey := fmt.Sprintf("WhisperTimes:%d", msg.SenderUserID) whisperKey := fmt.Sprintf("WhisperTimes:%d", msg.SenderUserID)
// 今日频次限制 // 今日频次限制
if res, _ := conf.Redis.Get(c, whisperKey).Result(); convert.StrTo(res).MustInt() >= MAX_WHISPER_NUM_DAILY { if res, _ := redisClient.Get(c, whisperKey).Result(); convert.StrTo(res).MustInt() >= MAX_WHISPER_NUM_DAILY {
return nil, errcode.TooManyWhisperNum return nil, errcode.TooManyWhisperNum
} }
@ -42,11 +41,11 @@ func CreateWhisper(c *gin.Context, msg *core.Message) (*core.Message, error) {
} }
// 写入当日(自然日)计数缓存 // 写入当日(自然日)计数缓存
conf.Redis.Incr(c, whisperKey).Result() redisClient.Incr(c, whisperKey).Result()
currentTime := time.Now() currentTime := time.Now()
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location()) endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
conf.Redis.Expire(c, whisperKey, endTime.Sub(currentTime)) redisClient.Expire(c, whisperKey, endTime.Sub(currentTime))
return msg, err return msg, err
} }

@ -501,8 +501,8 @@ func DeleteSearchPost(post *core.Post) error {
} }
func PushPostsToSearch(c *gin.Context) { func PushPostsToSearch(c *gin.Context) {
if ok, _ := conf.Redis.SetNX(c, "JOB_PUSH_TO_SEARCH", 1, time.Hour).Result(); ok { if ok, _ := redisClient.SetNX(c, "JOB_PUSH_TO_SEARCH", 1, time.Hour).Result(); ok {
defer conf.Redis.Del(c, "JOB_PUSH_TO_SEARCH") defer redisClient.Del(c, "JOB_PUSH_TO_SEARCH")
splitNum := 1000 splitNum := 1000
totalRows, _ := GetPostCount(&core.ConditionsT{ totalRows, _ := GetPostCount(&core.ConditionsT{

@ -13,7 +13,6 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gofrs/uuid" "github.com/gofrs/uuid"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/convert"
"github.com/rocboss/paopao-ce/pkg/errcode" "github.com/rocboss/paopao-ce/pkg/errcode"
@ -102,7 +101,7 @@ func DoLogin(ctx *gin.Context, param *AuthRequest) (*core.User, error) {
} }
if user.Model != nil && user.ID > 0 { if user.Model != nil && user.ID > 0 {
if errTimes, err := conf.Redis.Get(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID)).Result(); err == nil { if errTimes, err := redisClient.Get(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID)).Result(); err == nil {
if convert.StrTo(errTimes).MustInt() >= _MaxLoginErrTimes { if convert.StrTo(errTimes).MustInt() >= _MaxLoginErrTimes {
return nil, errcode.TooManyLoginError return nil, errcode.TooManyLoginError
} }
@ -116,14 +115,14 @@ func DoLogin(ctx *gin.Context, param *AuthRequest) (*core.User, error) {
} }
// 清空登录计数 // 清空登录计数
conf.Redis.Del(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID)) redisClient.Del(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID))
return user, nil return user, nil
} }
// 登录错误计数 // 登录错误计数
_, err = conf.Redis.Incr(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID)).Result() _, err = redisClient.Incr(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID)).Result()
if err == nil { if err == nil {
conf.Redis.Expire(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID), time.Hour).Result() redisClient.Expire(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID), time.Hour).Result()
} }
return nil, errcode.UnauthorizedAuthFailed return nil, errcode.UnauthorizedAuthFailed
@ -435,12 +434,12 @@ func SendPhoneCaptcha(ctx *gin.Context, phone string) error {
} }
// 写入计数缓存 // 写入计数缓存
conf.Redis.Incr(ctx, "PaoPaoSmsCaptcha:"+phone).Result() redisClient.Incr(ctx, "PaoPaoSmsCaptcha:"+phone).Result()
currentTime := time.Now() currentTime := time.Now()
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location()) endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
conf.Redis.Expire(ctx, "PaoPaoSmsCaptcha:"+phone, endTime.Sub(currentTime)) redisClient.Expire(ctx, "PaoPaoSmsCaptcha:"+phone, endTime.Sub(currentTime))
return nil return nil
} }

@ -5,11 +5,11 @@
package broker package broker
import ( import (
"github.com/rocboss/paopao-ce/internal/core"
"time" "time"
"github.com/rocboss/paopao-ce/internal/core"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/pkg/errcode" "github.com/rocboss/paopao-ce/pkg/errcode"
) )
@ -26,7 +26,7 @@ func CreateRecharge(userID, amount int64) (*core.WalletRecharge, error) {
} }
func FinishRecharge(ctx *gin.Context, id int64, tradeNo string) error { func FinishRecharge(ctx *gin.Context, id int64, tradeNo string) error {
if ok, _ := conf.Redis.SetNX(ctx, "PaoPaoRecharge:"+tradeNo, 1, time.Second*5).Result(); ok { if ok, _ := redisClient.SetNX(ctx, "PaoPaoRecharge:"+tradeNo, 1, time.Second*5).Result(); ok {
recharge, err := ds.GetRechargeByID(id) recharge, err := ds.GetRechargeByID(id)
if err != nil { if err != nil {
return err return err
@ -36,7 +36,7 @@ func FinishRecharge(ctx *gin.Context, id int64, tradeNo string) error {
// 标记为已付款 // 标记为已付款
err := ds.HandleRechargeSuccess(recharge, tradeNo) err := ds.HandleRechargeSuccess(recharge, tradeNo)
defer conf.Redis.Del(ctx, "PaoPaoRecharge:"+tradeNo) defer redisClient.Del(ctx, "PaoPaoRecharge:"+tradeNo)
if err != nil { if err != nil {
return err return err

@ -6,6 +6,7 @@ package api
import ( import (
"github.com/alimy/cfg" "github.com/alimy/cfg"
"github.com/go-redis/redis/v8"
"github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/internal/dao" "github.com/rocboss/paopao-ce/internal/dao"
@ -14,11 +15,13 @@ import (
) )
var ( var (
redisClient *redis.Client
alipayClient *alipay.Client alipayClient *alipay.Client
objectStorage core.ObjectStorageService objectStorage core.ObjectStorageService
) )
func Initialize() { func Initialize() {
redisClient = conf.MustRedis()
objectStorage = dao.ObjectStorageService() objectStorage = dao.ObjectStorageService()
if cfg.If("Alipay") { if cfg.If("Alipay") {

@ -14,7 +14,6 @@ import (
"github.com/afocus/captcha" "github.com/afocus/captcha"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gofrs/uuid" "github.com/gofrs/uuid"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/internal/servants/web/assets" "github.com/rocboss/paopao-ce/internal/servants/web/assets"
"github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/internal/servants/web/broker"
@ -65,7 +64,7 @@ func GetCaptcha(c *gin.Context) {
key := util.EncodeMD5(uuid.Must(uuid.NewV4()).String()) key := util.EncodeMD5(uuid.Must(uuid.NewV4()).String())
// 五分钟有效期 // 五分钟有效期
conf.Redis.SetEX(c, "PaoPaoCaptcha:"+key, password, time.Minute*5) redisClient.SetEX(c, "PaoPaoCaptcha:"+key, password, time.Minute*5)
response := app.NewResponse(c) response := app.NewResponse(c)
response.ToResponse(gin.H{ response.ToResponse(gin.H{
@ -85,14 +84,14 @@ func PostCaptcha(c *gin.Context) {
} }
// 验证图片验证码 // 验证图片验证码
if res, err := conf.Redis.Get(c.Request.Context(), "PaoPaoCaptcha:"+param.ImgCaptchaID).Result(); err != nil || res != param.ImgCaptcha { if res, err := redisClient.Get(c.Request.Context(), "PaoPaoCaptcha:"+param.ImgCaptchaID).Result(); err != nil || res != param.ImgCaptcha {
response.ToErrorResponse(errcode.ErrorCaptchaPassword) response.ToErrorResponse(errcode.ErrorCaptchaPassword)
return return
} }
conf.Redis.Del(c.Request.Context(), "PaoPaoCaptcha:"+param.ImgCaptchaID).Result() redisClient.Del(c.Request.Context(), "PaoPaoCaptcha:"+param.ImgCaptchaID).Result()
// 今日频次限制 // 今日频次限制
if res, _ := conf.Redis.Get(c.Request.Context(), "PaoPaoSmsCaptcha:"+param.Phone).Result(); convert.StrTo(res).MustInt() >= MAX_PHONE_CAPTCHA { if res, _ := redisClient.Get(c.Request.Context(), "PaoPaoSmsCaptcha:"+param.Phone).Result(); convert.StrTo(res).MustInt() >= MAX_PHONE_CAPTCHA {
response.ToErrorResponse(errcode.TooManyPhoneCaptchaSend) response.ToErrorResponse(errcode.TooManyPhoneCaptchaSend)
return return
} }

@ -19,7 +19,7 @@ import (
func RouteWeb(e *gin.Engine) { func RouteWeb(e *gin.Engine) {
oss := dao.ObjectStorageService() oss := dao.ObjectStorageService()
ds := &base.DaoServant{ ds := &base.DaoServant{
Redis: conf.Redis, Redis: conf.MustRedis(),
Ds: dao.DataService(), Ds: dao.DataService(),
Ts: dao.TweetSearchService(), Ts: dao.TweetSearchService(),
} }

Loading…
Cancel
Save