package redis import ( "errors" "git.tetele.net/tgo/helper" redisdb "github.com/gomodule/redigo/redis" ) //取值 func GetString(key string) (string, error) { c := GetConn() str, err := redisdb.String(c.Do("get", key)) CloseConn(c) return str, err } /* * 存值, * args,范围(key, value)或(key, value,expire) * 2020/06/06 */ func Set(args ...interface{}) (string, error) { c := GetConn() if len(args) < 2 { return "", errors.New("参数错误,至少需两个参数") } var err error var reply interface{} if len(args) > 2 && helper.ToInt(args[2]) > 0 { reply, err = c.Do("SET", args[0], args[1], "EX", args[2]) //设置过期时间 } else { reply, err = c.Do("SET", args[0], args[1]) } CloseConn(c) if err != nil { return "", err } ret, err := redisdb.String(reply, err) return ret, err } /** * 删除key */ func Del(key string) (int64, error) { c := GetConn() var err error var reply interface{} reply, err = c.Do("DEL", key) CloseConn(c) if err != nil { return 0, err } ret, err := redisdb.Int64(reply, err) return ret, err } /** * 设锁 * 2020/01/15 */ func SetNx(args ...interface{}) (int64, error) { c := GetConn() if len(args) < 2 { return 0, errors.New("参数错误,至少需两个参数") } var err error var result interface{} if len(args) > 2 && helper.ToInt(args[2]) > 0 { result, err = c.Do("SET", args[0],args[1],"EX",args[2],"NX") //设置过期时间 } else { result, err = c.Do("SETNX", args[0], args[1]) } if err != nil { return 0, err } CloseConn(c) if helper.ToStr(result) == "OK"{ return 1, nil } return 0,nil } /** * key是否存在 */ func Exists(key string) (int64, error) { c := GetConn() var err error var reply interface{} reply, err = c.Do("Exists", key) CloseConn(c) if err != nil { return 0, err } ret, err := redisdb.Int64(reply, err) return ret, err }