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.

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