redis.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package utils
  2. import (
  3. "context"
  4. "log"
  5. "strconv"
  6. "time"
  7. beego "github.com/beego/beego/v2/server/web"
  8. "github.com/go-redis/redis/v8"
  9. )
  10. var RedisClient *redis.Client
  11. func redisString(key string, fallback string) string {
  12. v, err := beego.AppConfig.String(key)
  13. if err != nil || v == "" {
  14. return fallback
  15. }
  16. return v
  17. }
  18. func redisInt(key string, fallback int) int {
  19. raw, err := beego.AppConfig.String(key)
  20. if err != nil || raw == "" {
  21. return fallback
  22. }
  23. v, err := strconv.Atoi(raw)
  24. if err != nil || v < 0 {
  25. log.Printf("invalid redis config %s=%q, fallback=%d", key, raw, fallback)
  26. return fallback
  27. }
  28. return v
  29. }
  30. func redisBool(key string, fallback bool) bool {
  31. raw, err := beego.AppConfig.String(key)
  32. if err != nil || raw == "" {
  33. return fallback
  34. }
  35. v, err := strconv.ParseBool(raw)
  36. if err != nil {
  37. log.Printf("invalid redis config %s=%q, fallback=%t", key, raw, fallback)
  38. return fallback
  39. }
  40. return v
  41. }
  42. func InitRedis() error {
  43. if !redisBool("redis_enable", false) {
  44. return nil
  45. }
  46. addr := redisString("redis_addr", "127.0.0.1:6379")
  47. password := redisString("redis_password", "")
  48. db := redisInt("redis_db", 0)
  49. poolSize := redisInt("redis_pool_size", 10)
  50. minIdleConns := redisInt("redis_min_idle_conns", 2)
  51. dialTimeoutMS := redisInt("redis_dial_timeout_ms", 5000)
  52. readTimeoutMS := redisInt("redis_read_timeout_ms", 3000)
  53. writeTimeoutMS := redisInt("redis_write_timeout_ms", 3000)
  54. pingTimeoutMS := redisInt("redis_ping_timeout_ms", 3000)
  55. client := redis.NewClient(&redis.Options{
  56. Addr: addr,
  57. Password: password,
  58. DB: db,
  59. PoolSize: poolSize,
  60. MinIdleConns: minIdleConns,
  61. DialTimeout: time.Duration(dialTimeoutMS) * time.Millisecond,
  62. ReadTimeout: time.Duration(readTimeoutMS) * time.Millisecond,
  63. WriteTimeout: time.Duration(writeTimeoutMS) * time.Millisecond,
  64. })
  65. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(pingTimeoutMS)*time.Millisecond)
  66. defer cancel()
  67. if err := client.Ping(ctx).Err(); err != nil {
  68. _ = client.Close()
  69. return err
  70. }
  71. RedisClient = client
  72. log.Printf("redis connected: addr=%s db=%d", addr, db)
  73. return nil
  74. }
  75. func CloseRedis() {
  76. if RedisClient == nil {
  77. return
  78. }
  79. _ = RedisClient.Close()
  80. }