Cache (redis)
The cache package provides an interface and implementation for caching data using Redis. This document explains how to use the cache package and its methods.
Base on redis/go-redis: Redis Go client (github.com)
Interface
go
type ICache interface {
Set(key string, value interface{}, expiration time.Duration) error
SetJSON(key string, value interface{}, expiration time.Duration) error
Get(dest interface{}, key string) error
GetJSON(dest interface{}, key string) error
Del(key string) error
Close()
}
Usage
Update .env
dotenv
CACHE_HOST=xxxxx
CACHE_PORT=6379
To create a new cache instance
go
// APIRun is the main function to start the application.
func APIRun() {
env := core.NewEnv()
// Connect to Redis
redis, err := core.NewCache(env.Config()).Connect()
if err != nil {
fmt.Fprintf(os.Stderr, "redis: %v", err)
os.Exit(1)
}
// Closing the Cache Connection
defer rdb.Close()
// Create a new HTTP server
e := core.NewHTTPServer(&core.HTTPContextOptions{
ContextOptions: &core.ContextOptions{
Cache: redis,
ENV: env,
},
})
// Register HTTP handlers
home.NewHomeHTTP(e)
// Start the HTTP server
core.StartHTTPServer(e, env)
}
Setting a Key-Value Pair
To set a key-value pair in the cache, use the Set
method:
go
func (c cache) Set(key string, value interface{}, expiration time.Duration) error
Example:
go
err := ctx.Cache().Set("mykey", "myvalue", time.Hour)
if err != nil {
// handle error
}
Getting a Value by Key
To retrieve a value from the cache by its key, use the Get
method:
go
func (c cache) Get(dest interface{}, key string) error
Example:
go
var value string
err := ctx.Cache().Get(&value, "mykey")
if err != nil {
// handle error
}
fmt.Println(value)
Deleting a Key
To delete a key from the cache, use the Del
method:
go
func (c cache) Del(key string) error
Example:
go
err := ctx.Cache().Del("mykey")
if err != nil {
// handle error
}
Setting a JSON Value
To set a JSON value in the cache, use the SetJSON
method:
go
func (c cache) SetJSON(key string, value interface{}, expiration time.Duration) error
Example:
go
data := struct {
Name string `json:"name"`
}{
Name: "John Doe",
}
err := ctx.Cache().SetJSON("myjson", data, time.Hour)
if err != nil {
// handle error
}
Getting a JSON Value
To retrieve a JSON value from the cache, use the GetJSON
method:
go
func (c cache) GetJSON(dest interface{}, key string) error
Example:
go
var data struct {
Name string `json:"name"`
}
err := ctx.Cache().GetJSON(&data, "myjson")
if err != nil {
// handle error
}
fmt.Println(data.Name)
Conclusion
This document explained how to use the cache package to interact with Redis for caching data. Use the provided methods to set, get, and delete key-value pairs, as well as JSON values, in the cache. Don't forget to close