如何用 redis-stack 存取和修改 json 数据

本文是redis json.set 命令的 golang 应用

package main

import (
    "context"
    "encoding/json"
    "errors"
    "fmt"

    "github.com/redis/go-redis/v9"
)

var ctx = context.Background()
var rdb *redis.Client

type Person struct {
    Name string
    Age  uint8
    Addr string
}

func main() {
    rdb = redis.NewClient(&redis.Options{
        Addr:     "localhost:16379",
        Password: "", // no password set
        DB:       0,  // use default DB
    })

    err := rdb.Set(ctx, "key", "value", 0).Err()
    if err != nil {
        panic(err)
    }
    //
    // cmd3, err := client.JSONSet(ctx, "index2", "$", `[0,1,2,3,4]`).Result()
    val1 := []int64{1, 2, 3, 4}
    key := "person"
    SetJsonData(key, "$", val1)
    val, err := rdb.JSONSet(ctx, key, "$", val1).Result()
    if err != nil {
        fmt.Printf("err %v\n", err)
    }
    fmt.Println("key", val)
    keyXiaoming := "xiaoming"
    xiaoming := Person{
        Name: "xiaoming",
        Age:  18,
        Addr: "beijing",
    }
    ret, err := SetJsonData(keyXiaoming, "$", xiaoming)
    ret = GetData(keyXiaoming, "$")
    fmt.Printf("get xiaoming ret %v ,err:  %v\n", ret, err)

    // 修改 name
    err1 := json.Unmarshal([]byte(ret), &xiaoming)
    fmt.Printf(" xiaoming to struct err :%v\n", err1)

    // 注意  这里val更新的时候必须要加上``(eg:`"zhang"`) ,直接写 "zhang" 会发生错误
    ret, err = SetJsonData(keyXiaoming, "$.Name", `"zhang"`)
    fmt.Printf("update name ret %v ,err:[%v]", ret, err)
    ret = GetData(keyXiaoming, "$")
    fmt.Printf("get newdata ret %v  ", ret)
    // 修改age
    ret, err = rdb.JSONNumIncrBy(ctx, keyXiaoming, "$.Age", 1).Result()
    // json.get  xiaoming
    // "{\"Name\":\"zhang\",\"Age\":19,\"Addr\":\"beijing\"}"
    fmt.Printf("update age ret [%v] ,err:[%v]", ret, err)

    // 新增一个字段 active
    ret, err = SetJsonData(keyXiaoming, "$.active", `"true"`)
    fmt.Printf("update active ret [%v] ,err:[%v]", ret, err)
    //get data from db
    fmt.Println("get data from db ", GetData(keyXiaoming, "$"))
    
}

func SetJsonData(key string, path string, val interface{}) (string, error) {
    cmd3, err := rdb.JSONSet(ctx, key, path, val).Result()
    if err != nil {
        fmt.Printf("err %v\n", err)
    }
    fmt.Println("key ", cmd3)
    return cmd3, err
}

// json get 数据
func GetData(key string, path string) string {
    val2, err := rdb.JSONGet(ctx, key, path).Result()
    if errors.Is(err, redis.Nil) {
        fmt.Println("key2 does not exist")
    } else if err != nil {
        fmt.Printf("get key %v  err %v \n ", key, err)
    } else {
        fmt.Println("key2", val2)
    }
    return val2
}


本文链接:参与评论 »

--EOF--

Comments