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.

77 lines
1.7 KiB

  1. package redis
  2. import (
  3. "log"
  4. "time"
  5. redisdb "github.com/gomodule/redigo/redis"
  6. )
  7. // 定义redis链接池
  8. var Pool *redisdb.Pool
  9. // redis服务地址,如需更改,在api服务中设置
  10. var RedisServerUrl string = "127.0.0.1:6379"
  11. // redis密码,如需更改,在api服务中设置
  12. var RedisPassword string = ""
  13. var MaxActive, MaxIdle int = 1, 1 //最大的激活连接数,最大的空闲连接数
  14. // func init() {
  15. // if Pool == nil {
  16. // RedisInit()
  17. // }
  18. // }
  19. func Conn() {
  20. RedisInit(RedisServerUrl, RedisPassword, MaxActive, MaxIdle)
  21. }
  22. /*
  23. * 初始化redis链接池
  24. * @param serverUrl 服务地址
  25. * @param password 密码
  26. * @param max 最大的激活连接数,最大的空闲连接数
  27. */
  28. func RedisInit(serverUrl, password string, max ...int) {
  29. if len(max) > 0 {
  30. MaxActive = max[0]
  31. }
  32. if len(max) > 1 {
  33. MaxIdle = max[1]
  34. }
  35. if serverUrl != "" {
  36. RedisServerUrl = serverUrl
  37. }
  38. if password != "" {
  39. RedisPassword = password
  40. }
  41. Pool = &redisdb.Pool{
  42. MaxIdle: MaxIdle, /*最大的空闲连接数*/
  43. MaxActive: MaxActive, /*最大的激活连接数*/
  44. Dial: redisConn,
  45. }
  46. }
  47. func redisConn() (redisdb.Conn, error) {
  48. dbOption := redisdb.DialDatabase(0)
  49. pwOption := redisdb.DialPassword(RedisPassword)
  50. // **重要** 设置读写超时
  51. readTimeout := redisdb.DialReadTimeout(time.Second * time.Duration(2))
  52. writeTimeout := redisdb.DialWriteTimeout(time.Second * time.Duration(5))
  53. conTimeout := redisdb.DialConnectTimeout(time.Second * time.Duration(2))
  54. c, err := redisdb.Dial("tcp", RedisServerUrl, dbOption, pwOption, readTimeout, writeTimeout, conTimeout)
  55. if err != nil {
  56. log.Println("redis connect failed", err)
  57. return nil, err
  58. } else {
  59. log.Println("redis connected", RedisServerUrl)
  60. }
  61. return c, nil
  62. }