Go语言:go-redis客户端读写哈希表(hash)的相关命令hset hget hgetall hdel的用法示例

  • Post author:
  • Post category:其他


package main

import (
        "fmt"
        "github.com/go-redis/redis"
)

func main() {
        client := redis.NewClient(&redis.Options{
                Addr:     "127.0.0.1:6380",
                Password: "",
                DB:       0,
        })

        ok1, err1 := client.HSet("key", "field1", "value1").Result()
        fmt.Printf("ok1=%v err1=%v\n", ok1, err1)
        ok2, err2 := client.HSet("key", "field2", "value2").Result()
        fmt.Printf("ok2=%v err2=%v\n", ok2, err2)
        ok3, err3 := client.HSet("key", "field3", "value3").Result()
        fmt.Printf("ok3=%v err3=%v\n", ok3, err3)

        value, err := client.HGet("key", "field2").Result()
        fmt.Printf("value of field2=%v err=%v\n", value, err)

        reply, err_hdel := client.HDel("key", "field2").Result()
        fmt.Printf("reply=%d err_del=%v\n", reply, err_hdel)

        values, err_hgetall := client.HGetAll("key").Result()
        fmt.Printf("all values=%v err_hgetall=%v\n", values, err_hgetall)
}

输出:

ok1=true err1=<nil>
ok2=true err2=<nil>
ok3=true err3=<nil>
value of field2=value2 err=<nil>
reply=1 err_del=<nil>
all values=map[field1:value1 field3:value3] err_hgetall=<nil>

如果key已经存在并且value的类型不是哈希表,则报如下错误:

ok1=false err1=WRONGTYPE Operation against a key holding the wrong kind of value
ok2=false err2=WRONGTYPE Operation against a key holding the wrong kind of value
ok3=false err3=WRONGTYPE Operation against a key holding the wrong kind of value
value of field2= err=WRONGTYPE Operation against a key holding the wrong kind of value
reply=0 err_del=WRONGTYPE Operation against a key holding the wrong kind of value
all values=map[] err_hgetall=WRONGTYPE Operation against a key holding the wrong kind of value



版权声明:本文为pengpengzhou原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。