rdshelper.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. * @description:
  3. * @Author: CP
  4. * @Date: 2021-01-27 11:00:27
  5. * @FilePath: \construction_management\datasource\rdshelper.go
  6. */
  7. package datasource
  8. import (
  9. "fmt"
  10. "log"
  11. "sync"
  12. "time"
  13. "github.com/gomodule/redigo/redis"
  14. "go.mod/conf"
  15. )
  16. var rdsLock sync.Mutex
  17. var cacheInstance *RedisConn
  18. // 封装成一个redis资源池
  19. type RedisConn struct {
  20. pool *redis.Pool
  21. showDebug bool
  22. }
  23. // 对外只有一个命令,封装了一个redis的命令
  24. func (rds *RedisConn) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  25. conn := rds.pool.Get()
  26. defer conn.Close()
  27. t1 := time.Now().UnixNano()
  28. reply, err = conn.Do(commandName, args...)
  29. if err != nil {
  30. e := conn.Err()
  31. if e != nil {
  32. log.Println("rdshelper Do", err, e)
  33. }
  34. }
  35. t2 := time.Now().UnixNano()
  36. if rds.showDebug {
  37. fmt.Printf("[redis] [info] [%dus]cmd=%s, err=%s, args=%v, reply=%s\n", (t2-t1)/1000, commandName, err, args, reply)
  38. }
  39. return reply, err
  40. }
  41. // 设置是否打印操作日志
  42. func (rds *RedisConn) ShowDebug(b bool) {
  43. rds.showDebug = b
  44. }
  45. // 得到唯一的redis缓存实例
  46. func InstanceCache() *RedisConn {
  47. if cacheInstance != nil {
  48. return cacheInstance
  49. }
  50. rdsLock.Lock()
  51. defer rdsLock.Unlock()
  52. if cacheInstance != nil {
  53. return cacheInstance
  54. }
  55. return NewCache()
  56. }
  57. // 重新实例化
  58. func NewCache() *RedisConn {
  59. pool := redis.Pool{
  60. Dial: func() (redis.Conn, error) {
  61. // redis.DialDatabase(5)
  62. c, err := redis.Dial("tcp", fmt.Sprintf("%s:%d", conf.RdsCache.Host, conf.RdsCache.Port), redis.DialDatabase(5))
  63. if err != nil {
  64. log.Fatal("rdshelper.NewCache Dial error ", err)
  65. return nil, err
  66. }
  67. return c, nil
  68. },
  69. TestOnBorrow: func(c redis.Conn, t time.Time) error {
  70. if time.Since(t) < time.Minute {
  71. return nil
  72. }
  73. _, err := c.Do("PING")
  74. return err
  75. },
  76. MaxIdle: 10000,
  77. MaxActive: 10000,
  78. IdleTimeout: 0,
  79. Wait: false,
  80. MaxConnLifetime: 0,
  81. }
  82. instance := &RedisConn{
  83. pool: &pool,
  84. }
  85. cacheInstance = instance
  86. cacheInstance.ShowDebug(true)
  87. //cacheInstance.ShowDebug(false)
  88. return cacheInstance
  89. }