You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.5KB

  1. package model
  2. import (
  3. "fmt"
  4. "github.com/go-redis/redis"
  5. "github.com/tal-tech/go-zero/core/logx"
  6. "gorm.io/driver/mysql"
  7. "gorm.io/gorm"
  8. "job_risk_third/config"
  9. "os"
  10. "time"
  11. )
  12. var (
  13. DB *gorm.DB
  14. Redis *redis.Client
  15. )
  16. func New(dsn string, cfg *gorm.Config) {
  17. DB, _ = newDbConnection(dsn, cfg)
  18. batchSyncTable([]interface{}{
  19. &TbRequestThirdLog{},
  20. })
  21. }
  22. func NewRedis(redisConfig config.RedisConfig) {
  23. Redis = connectRedis(redisConfig)
  24. }
  25. func newDbConnection(dsn string, cfg *gorm.Config) (db *gorm.DB, err error) {
  26. db, err = gorm.Open(mysql.Open(dsn), cfg)
  27. if err != nil {
  28. logx.Error(err)
  29. os.Exit(-1)
  30. }
  31. return
  32. }
  33. func batchSyncTable(tables []interface{}) {
  34. if len(tables) > 0 {
  35. for _, v := range tables {
  36. if err := DB.AutoMigrate(v); err != nil {
  37. logx.Error(err)
  38. return
  39. }
  40. }
  41. }
  42. return
  43. }
  44. func connectRedis(c config.RedisConfig) *redis.Client {
  45. client := redis.NewClient(&redis.Options{
  46. Addr: fmt.Sprintf("%s:%d", c.Address, c.Port),
  47. Password: c.Pass, // no password set
  48. DB: c.DB, // use default DB
  49. PoolSize: c.PoolSize, // Redis连接池大小
  50. MaxRetries: 3, // 最大重试次数
  51. IdleTimeout: 10 * time.Second, // 空闲链接超时时间
  52. })
  53. pong, err := client.Ping().Result()
  54. if err == redis.Nil {
  55. logx.Error("Redis异常,redis.Nil")
  56. } else if err != nil {
  57. logx.Errorf("Redis失败,%v", err)
  58. } else {
  59. logx.Infof("Redis连接成功,%s", pong)
  60. }
  61. return client
  62. }