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.

67 lines
1.4 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. var RedisServerUrl string = "127.0.0.1:6379"
  10. // func init() {
  11. // if Pool == nil {
  12. // RedisInit()
  13. // }
  14. // }
  15. func Conn(server_url ...string) {
  16. var url string = RedisServerUrl
  17. if len(server_url) > 0 {
  18. url = server_url[0]
  19. }
  20. RedisInit(url)
  21. }
  22. // 初始化redis链接池
  23. func RedisInit(serverUrl string, max ...int) {
  24. var MaxActive, MaxIdle int
  25. if len(max) > 0 {
  26. MaxActive = max[0]
  27. }
  28. if len(max) > 1 {
  29. MaxIdle = max[1]
  30. }
  31. if serverUrl != "" {
  32. RedisServerUrl = serverUrl
  33. }
  34. Pool = &redisdb.Pool{
  35. MaxIdle: MaxIdle, /*最大的空闲连接数*/
  36. MaxActive: MaxActive, /*最大的激活连接数*/
  37. Dial: redisConn,
  38. }
  39. }
  40. func redisConn() (redisdb.Conn, error) {
  41. dbOption := redisdb.DialDatabase(0)
  42. pwOption := redisdb.DialPassword("")
  43. // **重要** 设置读写超时
  44. readTimeout := redisdb.DialReadTimeout(time.Second * time.Duration(2))
  45. writeTimeout := redisdb.DialWriteTimeout(time.Second * time.Duration(5))
  46. conTimeout := redisdb.DialConnectTimeout(time.Second * time.Duration(2))
  47. c, err := redisdb.Dial("tcp", RedisServerUrl, dbOption, pwOption, readTimeout, writeTimeout, conTimeout)
  48. if err != nil {
  49. log.Println("redis connect failed", err)
  50. return nil, err
  51. } else {
  52. log.Println("redis connected", RedisServerUrl)
  53. }
  54. return c, nil
  55. }