redis.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package config
  2. import (
  3. "fmt"
  4. "github.com/go-redis/redis"
  5. "github.com/sirupsen/logrus"
  6. "os"
  7. "strconv"
  8. )
  9. var (
  10. LogRedis *redis.Client
  11. GameRedis *redis.Client
  12. RedisGroup map[int]*redis.Client
  13. )
  14. func InitRedis() {
  15. LogRedis = newRedis(os.Getenv("LOG_REDIS_ADDR"), os.Getenv("LOG_REDIS_PW"), os.Getenv("LOG_REDIS_DB"))
  16. RedisGroup = make(map[int]*redis.Client)
  17. GameRedis = newRedis(os.Getenv("REDIS_ADDR"), os.Getenv("REDIS_PW"), os.Getenv("REDIS_DB"))
  18. RedisGroup[1] = GameRedis
  19. failNum := 0
  20. for i := 2; i < 10000; i += 1 {
  21. addrKey := fmt.Sprintf("REDIS%v_ADDR", i)
  22. pwKey := fmt.Sprintf("REDIS%v_PW", i)
  23. dbKey := fmt.Sprintf("REDIS%v_DB", i)
  24. addr := os.Getenv(addrKey)
  25. if addr == "" {
  26. failNum += 1
  27. if failNum > 3 {
  28. return
  29. }
  30. continue
  31. }
  32. logrus.Printf("InitRedis %v", addrKey)
  33. RedisGroup[i] = newRedis(os.Getenv(addrKey), os.Getenv(pwKey), os.Getenv(dbKey))
  34. }
  35. }
  36. func newRedis(addr, password, db string) (client *redis.Client) {
  37. db2, _ := strconv.ParseUint(db, 10, 64)
  38. client = redis.NewClient(&redis.Options{
  39. Addr: addr,
  40. Password: password,
  41. DB: int(db2),
  42. MaxRetries: 1,
  43. })
  44. if _, err := client.Ping().Result(); err != nil {
  45. logrus.Panicf("连接Redis[%v]不成功, err:%+v", addr, err)
  46. }
  47. return
  48. }
  49. // PubMessage 发布
  50. func PubMessage(channel, msg string) {
  51. LogRedis.Publish(channel, msg)
  52. }
  53. // SubMessage 订阅
  54. func SubMessage(channel string, call func(msg *redis.Message)) {
  55. sub := LogRedis.Subscribe(channel)
  56. _, err := sub.Receive()
  57. if err != nil {
  58. panic(err)
  59. }
  60. for msg := range sub.Channel() {
  61. call(msg)
  62. }
  63. }