gredis.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package gredis provides convenient client for redis server.
  7. //
  8. // Redis Client.
  9. //
  10. // Redis Commands Official: https://redis.io/commands
  11. //
  12. // Redis Chinese Documentation: http://redisdoc.com/
  13. package gredis
  14. import (
  15. "fmt"
  16. "time"
  17. "github.com/gogf/gf/container/gmap"
  18. "github.com/gogf/gf/container/gvar"
  19. "github.com/gomodule/redigo/redis"
  20. )
  21. // Redis client.
  22. type Redis struct {
  23. pool *redis.Pool // Underlying connection pool.
  24. group string // Configuration group.
  25. config Config // Configuration.
  26. }
  27. // Redis connection.
  28. type Conn struct {
  29. redis.Conn
  30. }
  31. // Redis configuration.
  32. type Config struct {
  33. Host string
  34. Port int
  35. Db int
  36. Pass string // Password for AUTH.
  37. MaxIdle int // Maximum number of connections allowed to be idle (default is 10)
  38. MaxActive int // Maximum number of connections limit (default is 0 means no limit).
  39. IdleTimeout time.Duration // Maximum idle time for connection (default is 10 seconds, not allowed to be set to 0)
  40. MaxConnLifetime time.Duration // Maximum lifetime of the connection (default is 30 seconds, not allowed to be set to 0)
  41. ConnectTimeout time.Duration // Dial connection timeout.
  42. TLS bool // Specifies the config to use when a TLS connection is dialed.
  43. TLSSkipVerify bool // Disables server name verification when connecting over TLS
  44. }
  45. // Pool statistics.
  46. type PoolStats struct {
  47. redis.PoolStats
  48. }
  49. const (
  50. gDEFAULT_POOL_IDLE_TIMEOUT = 10 * time.Second
  51. gDEFAULT_POOL_CONN_TIMEOUT = 10 * time.Second
  52. gDEFAULT_POOL_MAX_IDLE = 10
  53. gDEFAULT_POOL_MAX_ACTIVE = 100
  54. gDEFAULT_POOL_MAX_LIFE_TIME = 30 * time.Second
  55. )
  56. var (
  57. // Pool map.
  58. pools = gmap.NewStrAnyMap(true)
  59. )
  60. // New creates a redis client object with given configuration.
  61. // Redis client maintains a connection pool automatically.
  62. func New(config Config) *Redis {
  63. // The MaxIdle is the most important attribute of the connection pool.
  64. // Only if this attribute is set, the created connections from client
  65. // can not exceed the limit of the server.
  66. if config.MaxIdle == 0 {
  67. config.MaxIdle = gDEFAULT_POOL_MAX_IDLE
  68. }
  69. // This value SHOULD NOT exceed the connection limit of redis server.
  70. if config.MaxActive == 0 {
  71. config.MaxActive = gDEFAULT_POOL_MAX_ACTIVE
  72. }
  73. if config.IdleTimeout == 0 {
  74. config.IdleTimeout = gDEFAULT_POOL_IDLE_TIMEOUT
  75. }
  76. if config.ConnectTimeout == 0 {
  77. config.ConnectTimeout = gDEFAULT_POOL_CONN_TIMEOUT
  78. }
  79. if config.MaxConnLifetime == 0 {
  80. config.MaxConnLifetime = gDEFAULT_POOL_MAX_LIFE_TIME
  81. }
  82. return &Redis{
  83. config: config,
  84. pool: pools.GetOrSetFuncLock(fmt.Sprintf("%v", config), func() interface{} {
  85. return &redis.Pool{
  86. Wait: true,
  87. IdleTimeout: config.IdleTimeout,
  88. MaxActive: config.MaxActive,
  89. MaxIdle: config.MaxIdle,
  90. MaxConnLifetime: config.MaxConnLifetime,
  91. Dial: func() (redis.Conn, error) {
  92. c, err := redis.Dial(
  93. "tcp",
  94. fmt.Sprintf("%s:%d", config.Host, config.Port),
  95. redis.DialConnectTimeout(config.ConnectTimeout),
  96. redis.DialUseTLS(config.TLS),
  97. redis.DialTLSSkipVerify(config.TLSSkipVerify),
  98. )
  99. if err != nil {
  100. return nil, err
  101. }
  102. // AUTH
  103. if len(config.Pass) > 0 {
  104. if _, err := c.Do("AUTH", config.Pass); err != nil {
  105. return nil, err
  106. }
  107. }
  108. // DB
  109. if _, err := c.Do("SELECT", config.Db); err != nil {
  110. return nil, err
  111. }
  112. return c, nil
  113. },
  114. // After the conn is taken from the connection pool, to test if the connection is available,
  115. // If error is returned then it closes the connection object and recreate a new connection.
  116. TestOnBorrow: func(c redis.Conn, t time.Time) error {
  117. _, err := c.Do("PING")
  118. return err
  119. },
  120. }
  121. }).(*redis.Pool),
  122. }
  123. }
  124. // NewFromStr creates a redis client object with given configuration string.
  125. // Redis client maintains a connection pool automatically.
  126. // The parameter <str> like:
  127. // 127.0.0.1:6379,0
  128. // 127.0.0.1:6379,0,password
  129. func NewFromStr(str string) (*Redis, error) {
  130. config, err := ConfigFromStr(str)
  131. if err != nil {
  132. return nil, err
  133. }
  134. return New(config), nil
  135. }
  136. // Close closes the redis connection pool,
  137. // it will release all connections reserved by this pool.
  138. // It is not necessary to call Close manually.
  139. func (r *Redis) Close() error {
  140. if r.group != "" {
  141. // If it is an instance object,
  142. // it needs to remove it from the instance Map.
  143. instances.Remove(r.group)
  144. }
  145. pools.Remove(fmt.Sprintf("%v", r.config))
  146. return r.pool.Close()
  147. }
  148. // Conn returns a raw underlying connection object,
  149. // which expose more methods to communicate with server.
  150. // **You should call Close function manually if you do not use this connection any further.**
  151. func (r *Redis) Conn() *Conn {
  152. return &Conn{r.pool.Get()}
  153. }
  154. // Alias of Conn, see Conn.
  155. // Deprecated.
  156. func (r *Redis) GetConn() *Conn {
  157. return r.Conn()
  158. }
  159. // SetMaxIdle sets the maximum number of idle connections in the pool.
  160. func (r *Redis) SetMaxIdle(value int) {
  161. r.pool.MaxIdle = value
  162. }
  163. // SetMaxActive sets the maximum number of connections allocated by the pool at a given time.
  164. // When zero, there is no limit on the number of connections in the pool.
  165. //
  166. // Note that if the pool is at the MaxActive limit, then all the operations will wait for
  167. // a connection to be returned to the pool before returning.
  168. func (r *Redis) SetMaxActive(value int) {
  169. r.pool.MaxActive = value
  170. }
  171. // SetIdleTimeout sets the IdleTimeout attribute of the connection pool.
  172. // It closes connections after remaining idle for this duration. If the value
  173. // is zero, then idle connections are not closed. Applications should set
  174. // the timeout to a value less than the server's timeout.
  175. func (r *Redis) SetIdleTimeout(value time.Duration) {
  176. r.pool.IdleTimeout = value
  177. }
  178. // SetMaxConnLifetime sets the MaxConnLifetime attribute of the connection pool.
  179. // It closes connections older than this duration. If the value is zero, then
  180. // the pool does not close connections based on age.
  181. func (r *Redis) SetMaxConnLifetime(value time.Duration) {
  182. r.pool.MaxConnLifetime = value
  183. }
  184. // Stats returns pool's statistics.
  185. func (r *Redis) Stats() *PoolStats {
  186. return &PoolStats{r.pool.Stats()}
  187. }
  188. // Do sends a command to the server and returns the received reply.
  189. // Do automatically get a connection from pool, and close it when the reply received.
  190. // It does not really "close" the connection, but drops it back to the connection pool.
  191. func (r *Redis) Do(commandName string, args ...interface{}) (interface{}, error) {
  192. conn := &Conn{r.pool.Get()}
  193. defer conn.Close()
  194. return conn.Do(commandName, args...)
  195. }
  196. // DoWithTimeout sends a command to the server and returns the received reply.
  197. // The timeout overrides the read timeout set when dialing the connection.
  198. func (r *Redis) DoWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (interface{}, error) {
  199. conn := &Conn{r.pool.Get()}
  200. defer conn.Close()
  201. return conn.DoWithTimeout(timeout, commandName, args...)
  202. }
  203. // DoVar returns value from Do as gvar.Var.
  204. func (r *Redis) DoVar(commandName string, args ...interface{}) (*gvar.Var, error) {
  205. return resultToVar(r.Do(commandName, args...))
  206. }
  207. // DoVarWithTimeout returns value from Do as gvar.Var.
  208. // The timeout overrides the read timeout set when dialing the connection.
  209. func (r *Redis) DoVarWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (*gvar.Var, error) {
  210. return resultToVar(r.DoWithTimeout(timeout, commandName, args...))
  211. }