redigo_adapter.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package redis
  2. import (
  3. "github.com/gomodule/redigo/redis"
  4. "github.com/spf13/viper"
  5. "strings"
  6. "time"
  7. )
  8. // redigo适配器
  9. type RedigoAdapter struct {
  10. pool *redis.Pool
  11. }
  12. // 返回redigo适配器新实例
  13. func NewRedigoAdapter(addr string) (IRedisAdapter, error) {
  14. opts := []redis.DialOption{redis.DialConnectTimeout(5 * time.Second)}
  15. password := viper.GetString("redis.password")
  16. if len(strings.TrimSpace(password)) > 0 {
  17. opts = append(opts, redis.DialPassword(strings.TrimSpace(password)))
  18. }
  19. pool, err := createPool(addr, opts...)
  20. if nil != err {
  21. return nil, err
  22. }
  23. return &RedigoAdapter{
  24. pool: pool,
  25. }, nil
  26. }
  27. // 创建redis连接池
  28. func createPool(addr string, opts ...redis.DialOption) (*redis.Pool, error) {
  29. maxIdle := viper.GetInt("redis.max_idle")
  30. maxActive := viper.GetInt("redis.max_active")
  31. idleTimeout := viper.GetDuration("redis.timeout")
  32. return &redis.Pool{
  33. MaxIdle: maxIdle,
  34. MaxActive: maxActive,
  35. IdleTimeout: idleTimeout,
  36. Dial: func() (redis.Conn, error) {
  37. if conn, err := redis.Dial("tcp", addr, opts...); nil != err {
  38. return nil, err
  39. } else {
  40. return conn, nil
  41. }
  42. },
  43. TestOnBorrow: func(c redis.Conn, t time.Time) error {
  44. _, err := c.Do("PING")
  45. return err
  46. },
  47. }, nil
  48. }
  49. // 关闭Redis连接
  50. func (a *RedigoAdapter) Close() error {
  51. return a.pool.Close()
  52. }
  53. // 执行Redis命令
  54. func (a *RedigoAdapter) Do(commandName string, args ...interface{}) (interface{}, error) {
  55. conn := a.pool.Get()
  56. defer func(conn redis.Conn) {
  57. _ = conn.Close()
  58. }(conn)
  59. if nil == conn {
  60. return nil, ErrRedisConnNil
  61. } else {
  62. return conn.Do(commandName, args...)
  63. }
  64. }