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.

80 lines
1.0 KiB

package redis
import (
"errors"
"strconv"
redisdb "github.com/gomodule/redigo/redis"
)
//监视key递减
func WatchSub(key, value string) (bool, error) {
var err error
c := GetConn()
reply, err := c.Do("WATCH", key)
if err != nil {
c.Do("UNWATCH")
return false, err
}
reply, err = c.Do("GET", key)
if err != nil {
c.Do("UNWATCH")
return false, err
}
stock, err := redisdb.Int64(reply, err)
if err != nil {
c.Do("UNWATCH")
return false, err
}
use, err := strconv.ParseInt(value, 10, 64)
if err != nil {
c.Do("UNWATCH")
return false, err
}
if stock < use {
c.Do("UNWATCH")
return false, errors.New("数量已不足")
}
reply, err = c.Do("MULTI")
if err != nil {
c.Do("UNWATCH")
return false, err
}
num := stock - use
reply, err = c.Do("SET", key, num)
if err != nil {
c.Do("UNWATCH")
return false, err
}
reply, err = c.Do("EXEC")
c.Do("UNWATCH")
CloseConn(c)
if err != nil {
return false, err
}
if reply != nil {
return true, err
}
return false, err
}