Introduction

The cache component provides a Redis cache adapter implementation for gcache. Redis cache is very useful in ensuring data consistency in multi-node environments, especially in scenarios such as Session sharing and database query caching.

Usage Example

  1. func ExampleCache_SetAdapter() {
  2. var (
  3. err error
  4. ctx = gctx.New()
  5. cache = gcache.New()
  6. redisConfig = &gredis.Config{
  7. Address: "127.0.0.1:6379",
  8. Db: 9,
  9. }
  10. cacheKey = `key`
  11. cacheValue = `value`
  12. )
  13. // Create redis client object.
  14. redis, err := gredis.New(redisConfig)
  15. if err != nil {
  16. panic(err)
  17. }
  18. // Create redis cache adapter and set it to cache object.
  19. cache.SetAdapter(gcache.NewAdapterRedis(redis))
  20. // Set and Get using cache object.
  21. err = cache.Set(ctx, cacheKey, cacheValue, time.Second)
  22. if err != nil {
  23. panic(err)
  24. }
  25. fmt.Println(cache.MustGet(ctx, cacheKey).String())
  26. // Get using redis client.
  27. fmt.Println(redis.MustDo(ctx, "GET", cacheKey).String())
  28. // Output:
  29. // value
  30. // value
  31. }

Notes

On Clear/Size Methods

First, the same gredis.Config will always connect to the same redis db, and since Redis itself doesn’t have data grouping features, when multiple gcache.Cache objects connect to the same redis db, they will share the entire redis db rather than having a separate group to store the current gcache.Cache object’s content. Therefore, operations like Clear and Size will act on the entire redis db instead of just the content in the current gcache.Cache object as with in-memory caches, which can be counterintuitive, so please use with caution.

Additionally, it is recommended to configure different db for usage when using Redis cache, rather than sharing a db with other business data.