Do Method

Do is a universal command interaction method that executes synchronous instructions by sending corresponding Redis API commands to the Redis Server to utilize the Redis Server services. The biggest feature of the Do method is its strong extensibility by interacting with the server using Redis commands, which can implement other commands not provided by the Redis operation methods. Usage example:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. )
  7. func main() {
  8. var (
  9. ctx = gctx.New()
  10. )
  11. v, _ := g.Redis().Do(ctx, "SET", "k", "v")
  12. fmt.Println(v.String())
  13. }

Automatic Serialization/Deserialization

When the given parameters are map, slice, or struct, gredis internally supports automatic json serialization and can use the conversion functions of gvar.Var for deserialization when reading data.

map Access

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/container/gvar"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/os/gctx"
  7. )
  8. func main() {
  9. var (
  10. ctx = gctx.New()
  11. err error
  12. result *gvar.Var
  13. key = "user"
  14. data = g.Map{
  15. "id": 10000,
  16. "name": "john",
  17. }
  18. )
  19. _, err = g.Redis().Do(ctx, "SET", key, data)
  20. if err != nil {
  21. panic(err)
  22. }
  23. result, err = g.Redis().Do(ctx,"GET", key)
  24. if err != nil {
  25. panic(err)
  26. }
  27. fmt.Println(result.Map())
  28. }

struct Access

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/container/gvar"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/os/gctx"
  7. )
  8. func main() {
  9. type User struct {
  10. Id int
  11. Name string
  12. }
  13. var (
  14. ctx = gctx.New()
  15. err error
  16. result *gvar.Var
  17. key = "user"
  18. user = g.Map{
  19. "id": 10000,
  20. "name": "john",
  21. }
  22. )
  23. _, err = g.Redis().Do(ctx, "SET", key, user)
  24. if err != nil {
  25. panic(err)
  26. }
  27. result, err = g.Redis().Do(ctx, "GET", key)
  28. if err != nil {
  29. panic(err)
  30. }
  31. var user2 *User
  32. if err = result.Struct(&user2); err != nil {
  33. panic(err)
  34. }
  35. fmt.Println(user2.Id, user2.Name)
  36. }