Do
方法
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
var (
err error
result *gvar.Var
key = "user"
ctx = gctx.New()
)
_, err = g.Redis().Do(ctx, "HSET", key, "id", 10000)
if err != nil {
panic(err)
}
_, err = g.Redis().Do(ctx,"HSET", key, "name", "john")
if err != nil {
panic(err)
}
result, err = g.Redis().Do(ctx,"HGETALL", key)
if err != nil {
panic(err)
}
fmt.Println(result.Map())
// May Output:
// map[id:10000 name:john]
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/util/gutil"
)
func main() {
type User struct {
Name string `json:"name"`
Sex int `json:"sex"`
Score int `json:"score"`
}
var (
ctx = gctx.New()
key = "user_100"
data = &User{
Name: "gf",
Sex: 0,
Score: 100,
}
)
_, err := g.Redis().Do(ctx,"HMSET", append(g.Slice{key}, gutil.StructToSlice(data)...)...)
if err != nil {
g.Log().Fatal(ctx, err)
}
v, err := g.Redis().Do(ctx,"HMGET", key, "name")
if err != nil {
g.Log().Fatal(ctx, err)
}
fmt.Println(v.Slice())
// May Output:
// [gf]
}
自动序列化/反序列化
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
type User struct {
Id int
Name string
}
var (
ctx = gctx.New()
err error
result *gvar.Var
key = "user"
user = g.Map{
"id": 10000,
"name": "john",
}
)
_, err = g.Redis().Do(ctx, "SET", key, user)
if err != nil {
panic(err)
}
result, err = g.Redis().Do(ctx, "GET", key)
if err != nil {
panic(err)
}
var user2 *User
if err = result.Struct(&user2); err != nil {
panic(err)
}