redis.go 998 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package redis
  2. import (
  3. "fmt"
  4. "github.com/go-redsync/redsync"
  5. "github.com/gomodule/redigo/redis"
  6. "time"
  7. )
  8. var pool *redis.Pool
  9. var redisLock *redsync.Redsync
  10. func InitRedis(host, port, password string) error {
  11. pool = &redis.Pool{
  12. MaxIdle: 20,
  13. IdleTimeout: 240 * time.Second,
  14. MaxActive: 50,
  15. Dial: func() (redis.Conn, error) {
  16. c, err := redis.Dial("tcp", fmt.Sprintf("%s:%s", host, port))
  17. if err != nil {
  18. return nil, err
  19. }
  20. if password != "" {
  21. if _, err := c.Do("AUTH", password); err != nil {
  22. c.Close()
  23. return nil, err
  24. }
  25. }
  26. return c, err
  27. },
  28. TestOnBorrow: func(c redis.Conn, t time.Time) error {
  29. _, err := c.Do("PING")
  30. return err
  31. },
  32. }
  33. redisLock = redsync.New([]redsync.Pool{pool})
  34. return nil
  35. }
  36. func GetRedisConn() (redis.Conn, error) {
  37. conn := pool.Get()
  38. return conn, conn.Err()
  39. }
  40. func GetRedisLock(key string, expireTime time.Duration) *redsync.Mutex {
  41. return redisLock.NewMutex(key, redsync.SetExpiry(expireTime))
  42. }