github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/mq/redis/redis_conn.go (about) 1 package redis 2 3 import ( 4 "github.com/gomodule/redigo/redis" 5 "github.com/sirupsen/logrus" 6 ) 7 8 func ConnRedis(pool *redis.Pool) *RedisConn { 9 return &RedisConn{ 10 pool: pool, 11 } 12 } 13 14 type RedisConn struct { 15 pool *redis.Pool 16 commands []*redisCommand 17 } 18 19 type redisCommand struct { 20 cmd string 21 args []interface{} 22 } 23 24 func (c *RedisConn) Do(cmd string, args ...interface{}) (interface{}, error) { 25 conn := c.pool.Get() 26 defer conn.Close() 27 28 res, err := conn.Do(cmd, args...) 29 if err != nil { 30 logrus.WithField("error", err.Error()).Println(append([]interface{}{cmd}, args...)) 31 return nil, err 32 } 33 34 return res, err 35 } 36 37 func (c *RedisConn) Send(cmd string, args ...interface{}) { 38 c.commands = append(c.commands, &redisCommand{ 39 cmd: cmd, 40 args: args, 41 }) 42 } 43 44 func (c *RedisConn) Exec() (interface{}, error) { 45 if len(c.commands) == 0 { 46 return nil, nil 47 } 48 conn := c.pool.Get() 49 defer conn.Close() 50 51 c.Send("MULTI") 52 53 for _, cmd := range c.commands { 54 err := conn.Send(cmd.cmd, cmd.args...) 55 if err != nil { 56 return nil, err 57 } 58 } 59 60 res, err := conn.Do("EXEC") 61 if err != nil { 62 logrus.WithField("error", err.Error()).Print() 63 return nil, err 64 } 65 66 c.commands = nil 67 68 return res, err 69 }