|
- package model
-
- import (
- "fmt"
- "github.com/go-redis/redis"
- "github.com/tal-tech/go-zero/core/logx"
- "gorm.io/driver/mysql"
- "gorm.io/gorm"
- "job_risk_third/config"
- "os"
- "time"
- )
-
- var (
- DB *gorm.DB
- Redis *redis.Client
- )
-
- func New(dsn string, cfg *gorm.Config) {
- DB, _ = newDbConnection(dsn, cfg)
- batchSyncTable([]interface{}{
- &TbRequestThirdLog{},
- })
- }
-
- func NewRedis(redisConfig config.RedisConfig) {
- Redis = connectRedis(redisConfig)
-
- }
-
- func newDbConnection(dsn string, cfg *gorm.Config) (db *gorm.DB, err error) {
- db, err = gorm.Open(mysql.Open(dsn), cfg)
- if err != nil {
- logx.Error(err)
- os.Exit(-1)
- }
- return
- }
-
- func batchSyncTable(tables []interface{}) {
- if len(tables) > 0 {
- for _, v := range tables {
- if err := DB.AutoMigrate(v); err != nil {
- logx.Error(err)
- return
- }
- }
- }
- return
- }
-
- func connectRedis(c config.RedisConfig) *redis.Client {
- client := redis.NewClient(&redis.Options{
- Addr: fmt.Sprintf("%s:%d", c.Address, c.Port),
- Password: c.Pass, // no password set
- DB: c.DB, // use default DB
- PoolSize: c.PoolSize, // Redis连接池大小
- MaxRetries: 3, // 最大重试次数
- IdleTimeout: 10 * time.Second, // 空闲链接超时时间
- })
- pong, err := client.Ping().Result()
- if err == redis.Nil {
- logx.Error("Redis异常,redis.Nil")
- } else if err != nil {
- logx.Errorf("Redis失败,%v", err)
- } else {
- logx.Infof("Redis连接成功,%s", pong)
- }
- return client
- }
|