redispool.go 672 B

123456789101112131415161718192021222324252627282930313233343536
  1. package redispool
  2. import (
  3. "github.com/garyburd/redigo/redis"
  4. "time"
  5. )
  6. var mapRedisPool map[string]*redis.Pool
  7. // GetClient get a redis connection by host
  8. func GetClient(host string) (redis.Conn, error) {
  9. pool, exist := mapRedisPool[host]
  10. if !exist {
  11. pool = &redis.Pool{
  12. MaxIdle: 10,
  13. Dial: func() (redis.Conn, error) {
  14. c, err := redis.Dial("tcp", host)
  15. if err != nil {
  16. return nil, err
  17. }
  18. return c, err
  19. },
  20. TestOnBorrow: func(c redis.Conn, t time.Time) error {
  21. _, err := c.Do("PING")
  22. return err
  23. },
  24. }
  25. mapRedisPool[host] = pool
  26. }
  27. return pool.Get(), nil
  28. }
  29. func init() {
  30. mapRedisPool = make(map[string]*redis.Pool)
  31. }