add get/set util

This commit is contained in:
Sinh 2022-01-27 10:10:02 +07:00
parent 3ad9d74dee
commit c43c50b76c
2 changed files with 27 additions and 1 deletions

View File

@ -1,6 +1,9 @@
package redisdb package redisdb
import "context" import (
"context"
"encoding/json"
)
// GetValueByKey ... // GetValueByKey ...
func GetValueByKey(ctx context.Context, key string) string { func GetValueByKey(ctx context.Context, key string) string {
@ -11,3 +14,15 @@ func GetValueByKey(ctx context.Context, key string) string {
value, _ := cmd.Result() value, _ := cmd.Result()
return value return value
} }
// GetJSON ...
func GetJSON(ctx context.Context, key string, result interface{}) (ok bool) {
v := GetValueByKey(ctx, key)
if v == "" {
return false
}
if err := json.Unmarshal([]byte(v), result); err != nil {
return false
}
return true
}

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"time"
) )
// SetKeyValue ... // SetKeyValue ...
@ -15,3 +16,13 @@ func SetKeyValue(ctx context.Context, key string, value interface{}) {
} }
rdb.Set(ctx, key, b, 0) rdb.Set(ctx, key, b, 0)
} }
// SetTTL ...
func SetTTL(ctx context.Context, key string, value interface{}, d time.Duration) {
b, err := json.Marshal(value)
if err != nil {
fmt.Println("redisdb - SetTTL error", err.Error())
return
}
rdb.Set(ctx, key, b, d)
}