package rediscontroll import ( "fmt" "github.com/go-redis/redis/v8" ) /** *哈希(hash)类型操作 */ /* 为哈希表中的字段赋值 。 单一设置 @hashName 集合名称 @hashKey 哈希键 @hashVal 要添加的值 */ func HashAdd(rdb *redis.Client, hashName, hashKey, hashVal string) bool { // rdb := RedisInit() err := rdb.HSet(ctx, hashName, hashKey, hashVal).Err() if err != nil { fmt.Printf("%v\n", err) return false } return true } /* 同时将多个 field-value (字段-值)对设置到哈希表中。 @hashName 集合名称 @hashVal 要添加的键与值 */ func HashMsetAdd(rdb *redis.Client, hashName string, hashVal map[string]interface{}) bool { // rdb := RedisInit() err := rdb.HMSet(ctx, hashName, hashVal).Err() // err := rdb.HMSet(ctx, "userfg", hashVal).Err() if err != nil { fmt.Printf("错误=========》%v\n", err) return false } // fmt.Printf("错误sss=========》%v\n", hashVal) return true } /* 返回哈希表中指定字段的值。 @hashName 集合名称 @hashKey 哈希键 */ func HashGet(rdb *redis.Client, hashName, hashKey string) (string, bool) { // rdb := RedisInit() val, err := rdb.HGet(ctx, hashName, hashKey).Result() if err != nil { fmt.Printf("%v\n", err) return "", false } return val, true } /* 返回哈希表中,所有的字段和值。 @hashName 集合名称 @hashKey 哈希键 */ func HashGetAll(rdb *redis.Client, hashName string) (map[string]string, bool) { // rdb := RedisInit() val, err := rdb.HGetAll(ctx, hashName).Result() if err != nil { fmt.Printf("%v\n", err) return val, false } if len(val) == 0 { return val, false } return val, true } /* 删除哈希表 key 中的一个或多个指定字段,不存在的字段将被忽略 @hashName 集合名称 @hashKey 哈希键 */ func HashDel(rdb *redis.Client, hashName, hashKey string) bool { // rdb := RedisInit() _, err := rdb.HDel(ctx, hashName, hashKey).Result() if err != nil { return false } return true } /* 查看哈希表的指定字段是否存在。 @hashName 集合名称 @hashKey 哈希键 */ func HashExists(rdb *redis.Client, hashName, hashKey string) bool { // rdb := RedisInit() _, err := rdb.HExists(ctx, hashName, hashKey).Result() if err != nil { return false } return true } /* 获取哈希表中字段的数量。 @hashName 集合名称 @hashKey 哈希键 */ func HashLen(rdb *redis.Client, hashName string) (int64, bool) { // rdb := RedisInit() val, err := rdb.HLen(ctx, hashName).Result() if err != nil { return val, false } return val, true }