redis.go 833 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package initialize
  2. import (
  3. "context"
  4. "server/global"
  5. "github.com/redis/go-redis/v9"
  6. "go.uber.org/zap"
  7. )
  8. func Redis() {
  9. redisCfg := global.GVA_CONFIG.Redis
  10. var client redis.UniversalClient
  11. // 使用集群模式
  12. if redisCfg.UseCluster {
  13. client = redis.NewClusterClient(&redis.ClusterOptions{
  14. Addrs: redisCfg.ClusterAddrs,
  15. Password: redisCfg.Password,
  16. })
  17. } else {
  18. // 使用单例模式
  19. client = redis.NewClient(&redis.Options{
  20. Addr: redisCfg.Addr,
  21. Password: redisCfg.Password,
  22. DB: redisCfg.DB,
  23. })
  24. }
  25. pong, err := client.Ping(context.Background()).Result()
  26. if err != nil {
  27. global.GVA_LOG.Error("redis connect ping failed, err:", zap.Error(err))
  28. panic(err)
  29. } else {
  30. global.GVA_LOG.Info("redis connect ping response:", zap.String("pong", pong))
  31. global.GVA_REDIS = client
  32. }
  33. }