Introduction

gcache is a module providing unified cache management, offering developers a customizable and flexible cache adapter interface, with a default high-speed in-memory cache adapter implementation.

Usage:

  1. import "github.com/gogf/gf/v2/os/gcache"

Interface Documentation:

https://pkg.go.dev/github.com/gogf/gf/v2/os/gcache

Brief Introduction:

  1. gcache provides a default high-speed in-memory cache object, which can be operated by package methods or created using the New method. When using cache functions via package methods, operations are on a globally provided gcache.Cache object, hence be cautious of global key name collisions in use.

  2. The key type used in gcache is interface{}, not string, meaning any variable type can be used as a key name. However, it is generally recommended to use string or []byte as key names and to unify the key name data type for maintenance purposes.

  3. The key-value type stored by gcache is interface{}, meaning any data type can be stored. When data is retrieved, it is returned as interface{}. If conversion to other types is needed, gcache‘s Get* methods can conveniently obtain common types. Note, if you are sure that in-memory cache is being used, you can directly use assertions for type conversion; otherwise, it is recommended to use the returned generic object’s corresponding method for type conversion.

  4. Additionally, note that the cache expiration time parameter duration in gcache is of type time.Duration. When setting a cache variable, duration = 0 means no expiration, duration < 0 means immediate expiration, and duration > 0 means timeout expiration.

Notes

About Key Name Data Types

You may notice that the data types of key-value pairs in the cache component are interface{}. This design aims for generality and ease of use, but requires attention to interface{} comparison: true matching requires both data and type to be equal. Here’s an example.

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/os/gcache"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. )
  7. func main() {
  8. var (
  9. ctx = gctx.New()
  10. key1 int32 = 1
  11. key2 float64 = 1
  12. value = `value`
  13. )
  14. _ = gcache.Set(ctx, key1, value, 0)
  15. fmt.Println(gcache.MustGet(ctx, key1).Val())
  16. fmt.Println(gcache.MustGet(ctx, key2).Val())
  17. }

After execution, the console outputs:

  1. <nil>

As you can see, although key1 and key2 have the same value, their types are different, so key2 cannot be used to obtain the key-value pair.

About Retrieving Object Key-Values

Since the key-value type is also interface{}, it is often converted to the desired data type after retrieval. A common conversion method is direct type assertion, but this carries a risk. The gcache component uses an adapter interface design pattern, meaning the implementation (besides the default in-memory adapter) often changes the original data type (non-memory implementations often involve serialization/deserialization storage). Thus, direct type assertion for data type conversion is not recommended.

To improve key-value retrieval, the cache component does not directly return interface{} but a framework generic *gvar.Var object, allowing developers to convert to the needed data type based on business scenarios. This is particularly useful for object cache storage and reading scenarios. Here’s an example:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/os/gcache"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. )
  7. func main() {
  8. type User struct {
  9. Id int
  10. Name string
  11. Site string
  12. }
  13. var (
  14. ctx = gctx.New()
  15. user *User
  16. key = `UserKey`
  17. value = &User{
  18. Id: 1,
  19. Name: "GoFrame",
  20. Site: "https://goframe.org",
  21. }
  22. )
  23. err := gcache.Set(ctx, key, value, 0)
  24. if err != nil {
  25. panic(err)
  26. }
  27. v, err := gcache.Get(ctx, key)
  28. if err != nil {
  29. panic(err)
  30. }
  31. if err = v.Scan(&user); err != nil {
  32. panic(err)
  33. }
  34. fmt.Printf(`%#v`, user)
  35. }

After execution, the console outputs:

  1. &main.User{Id:1, Name:"GoFrame", Site:"https://goframe.org"}

Documentation

📄️ Caching - InterfaceThe interface design and implementation of the cache management component in the GoFrame framework provide the Adapter interface, allowing developers to flexibly register and customize cache management objects, achieving seamless integration of different caching strategies. It details how to register and obtain interface implementations through SetAdapter and GetAdapter methods.

📄️ Caching - In-MemoryUsing in-memory caching with the GoFrame framework for efficient cache management, including basic usage, expiration control, the use of GetOrSetFunc functions, and LRU cache eviction control. Through example code, it demonstrates how to set caches, retrieve cache values, and perform concurrency control, aiming to help users optimize program performance.

📄️ Caching - RedisThe cache management module in the GoFrame framework focuses on the implementation and usage of the Redis cache adapter. It provides examples on ensuring data consistency in multi-node environments. Detailed steps on setting up Redis clients and using Redis cache adapters are given, and the operation notes for Clear and Size methods in multi-object connections are discussed. It is also recommended to configure independent Redis DBs for different business scenarios.

📄️ Caching - MethodsMethods for using cache management in the GoFrame framework, including basic set and get operations, adapter setup methods, and cache update strategies. Users can learn how to efficiently manage and operate cache data in the GoFrame framework through example code.