usermngmt/cache/cache.go

68 lines
1.1 KiB
Go
Raw Normal View History

2021-11-11 03:20:08 +00:00
package cache
import (
2021-12-08 04:42:31 +00:00
"context"
"encoding/json"
"fmt"
2021-11-11 03:20:08 +00:00
"log"
"time"
2021-12-08 04:42:31 +00:00
"github.com/go-redis/redis/v8"
"github.com/logrusorgru/aurora"
2021-11-11 03:20:08 +00:00
)
2021-12-08 04:42:31 +00:00
var (
c *redis.Client
)
2021-11-11 03:20:08 +00:00
// Init ...
2021-12-08 04:42:31 +00:00
func Init(uri, pwd string) {
c = redis.NewClient(&redis.Options{
Addr: uri,
Password: pwd,
DB: 0, // use default DB
})
// Test
_, err := c.Ping(context.Background()).Result()
2021-11-11 03:20:08 +00:00
if err != nil {
2021-12-08 04:42:31 +00:00
log.Fatal("Cannot connect to redis", uri, err)
2021-11-11 03:20:08 +00:00
}
2021-12-08 04:42:31 +00:00
fmt.Println(aurora.Green("*** CONNECTED TO REDIS: " + uri))
2021-11-11 08:16:17 +00:00
// Cache roles
Roles()
2021-11-11 03:20:08 +00:00
}
// GetInstance ...
2021-12-08 04:42:31 +00:00
func GetInstance() *redis.Client {
return c
}
// SetKeyValue ...
func SetKeyValue(key string, value interface{}, expiration time.Duration) error {
ctx := context.Background()
dataByte, _ := json.Marshal(value)
r := c.Set(ctx, key, dataByte, expiration)
return r.Err()
}
// GetValueByKey ...
func GetValueByKey(key string) ([]byte, error) {
ctx := context.Background()
return c.Get(ctx, key).Bytes()
2021-11-11 03:20:08 +00:00
}
2023-04-15 08:35:55 +00:00
func GetJSON(key string, result interface{}) bool {
v, err := GetValueByKey(key)
if err != nil {
return false
}
if err = json.Unmarshal(v, result); err != nil {
return false
}
return true
}