rdshelper.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. c, err := redis.Dial("tcp", fmt.Sprintf("%s:%d", conf.RdsCache.Host, conf.RdsCache.Port))
  62. if err != nil {
  63. log.Fatal("rdshelper.NewCache Dial error ", err)
  64. return nil, err
  65. }
  66. return c, nil
  67. },
  68. TestOnBorrow: func(c redis.Conn, t time.Time) error {
  69. if time.Since(t) < time.Minute {
  70. return nil
  71. }
  72. _, err := c.Do("PING")
  73. return err
  74. },
  75. MaxIdle: 10000,
  76. MaxActive: 10000,
  77. IdleTimeout: 0,
  78. Wait: false,
  79. MaxConnLifetime: 0,
  80. }
  81. instance := &RedisConn{
  82. pool: &pool,
  83. }
  84. cacheInstance = instance
  85. cacheInstance.ShowDebug(true)
  86. //cacheInstance.ShowDebug(false)
  87. return cacheInstance
  88. }