package redis import ( "errors" redisdb "github.com/gomodule/redigo/redis" ) /* * 存值 * key 域 * value 值 * 2021/08/31 */ func SAdd(key string, value interface{}) (int64, error) { c := GetConn() reply, err := c.Do("SADD", key, value) CloseConn(c) if err != nil { return 0, err } else { return redisdb.Int64(reply, nil) } } /* * 删除hash值 */ func SRem(key, value interface{}) (int64, error) { c := GetConn() reply, err := c.Do("SREM", key, value) CloseConn(c) if err != nil { return 0, err } else { return redisdb.Int64(reply, nil) } } /** * 集合键是否存在 * key 域 * field 名 */ func SIsmember(key, value interface{}) (int64, error) { c := GetConn() reply, err := c.Do("SISMEMBER", key, value) CloseConn(c) if err != nil { return 0, err } else { return redisdb.Int64(reply, nil) } } /** * 集合成员数量 */ func SCard(key interface{}) (int64, error) { c := GetConn() reply, err := c.Do("SCard", key) CloseConn(c) if err != nil { return 0, err } else { return redisdb.Int64(reply, nil) } } //hash取值,返回[]byte func SMembers(key string) ([]byte, error) { c := GetConn() ret, err := c.Do("SMEMBERS", key) reply := make([]byte, 0) if err == nil { reply, err = redisdb.Bytes(ret, err) } CloseConn(c) return reply, err } func ZAdd(key, score, member string) (int64, error) { c := GetConn() reply, err := c.Do("ZADD", key, score, member) CloseConn(c) if err != nil { return 0, err } else { return redisdb.Int64(reply, nil) } } func ZIncrBy(key, inc, member string) (int64, error) { c := GetConn() reply, err := c.Do("ZINCRBY", key, inc, member) CloseConn(c) if err != nil { return 0, err } else { return redisdb.Int64(reply, nil) } } func ZRange(key string, start, stop int64) ([]map[string]string, error) { c := GetConn() defer CloseConn(c) values, err := redisdb.Values(c.Do("ZRANGE", key, start, stop, "WITHSCORES")) if err != nil { return nil, err } if len(values)%2 != 0 { return nil, errors.New("redigo: ZRange expects even number of values result") } var l []map[string]string for i := 0; i < len(values); i += 2 { key, okKey := values[i].([]byte) value, okValue := values[i+1].([]byte) if !okKey || !okValue { return nil, errors.New("redigo: ZRange key not a bulk string value") } l = append(l, map[string]string{ "member": string(key), "score": string(value), }) } return l, nil } func ZScan(key, field string, len int64) ([]string, error) { c := GetConn() defer CloseConn(c) zscanResult, err := redisdb.Values(c.Do("ZSCAN", key, "0", "MATCH", field, "COUNT", len)) if err != nil { return nil, err } var cursor int var membersAndScores []string var member []string redisdb.Scan(zscanResult, &cursor, &membersAndScores) for i, v := range membersAndScores { if i%2 == 0 { member = append(member, v) } } return member, nil }