redis操作
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.2 KiB

  1. package redis
  2. import (
  3. "log"
  4. "time"
  5. "git.tetele.net/tgo/conf"
  6. redisdb "github.com/gomodule/redigo/redis"
  7. )
  8. // 定义redis链接池
  9. var Pool *redisdb.Pool
  10. // func init() {
  11. // if Pool == nil {
  12. // RedisInit()
  13. // }
  14. // }
  15. // 初始化redis链接池
  16. func RedisInit(max ...int) {
  17. var MaxActive, MaxIdle int
  18. if len(max) > 0 {
  19. MaxActive = max[0]
  20. }
  21. if len(max) > 1 {
  22. MaxIdle = max[1]
  23. }
  24. Pool = &redisdb.Pool{
  25. MaxIdle: MaxIdle, /*最大的空闲连接数*/
  26. MaxActive: MaxActive, /*最大的激活连接数*/
  27. Dial: redisConn,
  28. }
  29. }
  30. func redisConn() (redisdb.Conn, error) {
  31. var url string = conf.REDIS_SERVER
  32. if url == "" {
  33. url = "127.0.0.1:6379"
  34. }
  35. dbOption := redisdb.DialDatabase(0)
  36. pwOption := redisdb.DialPassword("")
  37. // **重要** 设置读写超时
  38. readTimeout := redisdb.DialReadTimeout(time.Second * time.Duration(2))
  39. writeTimeout := redisdb.DialWriteTimeout(time.Second * time.Duration(5))
  40. conTimeout := redisdb.DialConnectTimeout(time.Second * time.Duration(2))
  41. c, err := redisdb.Dial("tcp", url, dbOption, pwOption, readTimeout, writeTimeout, conTimeout)
  42. if err != nil {
  43. log.Println("redis server connect failed", err)
  44. return nil, err
  45. }
  46. return c, nil
  47. }