gredis adopts an interface-based design, offering strong flexibility and extensibility.

Interface Definition

https://pkg.go.dev/github.com/gogf/gf/v2/database/gredis#Adapter

  1. // SetAdapter sets custom adapter for current redis client.
  2. func (r *Redis) SetAdapter(adapter Adapter)
  3. // GetAdapter returns the adapter that is set in current redis client.
  4. func (r *Redis) GetAdapter() Adapter

Custom Redis Adapter

The framework community component provides a default implementation of the Redis Adapter. If developers need to implement a custom Redis Adapter or want to override certain methods, they can extend based on this implementation.

Let’s look at an example where we implement a custom Redis Adapter and override its underlying Do method. To simplify the example, we print a log in the custom Do method, and subsequent logic follows the community Redis Adapter implementation.

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/contrib/nosql/redis/v2"
  6. "github.com/gogf/gf/v2/container/gvar"
  7. "github.com/gogf/gf/v2/database/gredis"
  8. "github.com/gogf/gf/v2/frame/g"
  9. "github.com/gogf/gf/v2/os/gctx"
  10. )
  11. var (
  12. ctx = gctx.New()
  13. group = "cache"
  14. config = gredis.Config{
  15. Address: "127.0.0.1:6379",
  16. Db: 1,
  17. }
  18. )
  19. // MyRedis description
  20. type MyRedis struct {
  21. *redis.Redis
  22. }
  23. // Do implements and overwrites the underlying function Do from Adapter.
  24. func (r *MyRedis) Do(ctx context.Context, command string, args ...interface{}) (*gvar.Var, error) {
  25. fmt.Println("MyRedis Do:", command, args)
  26. return r.Redis.Do(ctx, command, args...)
  27. }
  28. func main() {
  29. gredis.RegisterAdapterFunc(func(config *gredis.Config) gredis.Adapter {
  30. r := &MyRedis{redis.New(config)}
  31. r.AdapterOperation = r // This is necessary.
  32. return r
  33. })
  34. gredis.SetConfig(&config, group)
  35. _, err := g.Redis(group).Set(ctx, "key", "value")
  36. if err != nil {
  37. g.Log().Fatal(ctx, err)
  38. }
  39. value, err := g.Redis(group).Get(ctx, "key")
  40. if err != nil {
  41. g.Log().Fatal(ctx, err)
  42. }
  43. fmt.Println(value.String())
  44. }

After execution, the terminal outputs:

  1. MyRedis Do: Set [key value]
  2. MyRedis Do: Get [key]
  3. value