feat: 添加 database - cache(redis)

This commit is contained in:
zhaoyupeng
2025-06-18 18:44:45 +08:00
parent 7dd48c0c50
commit edce9fe73f
8 changed files with 475 additions and 9 deletions

96
database/cache/cache.go vendored Normal file
View File

@ -0,0 +1,96 @@
package cache
import (
"context"
"encoding/json"
"errors"
"sync"
"time"
)
type encoded_value interface {
MarshalBinary() ([]byte, error)
}
type decoded_value interface {
UnmarshalBinary(bs []byte) error
}
type Scanner interface {
Scan(model any) error
}
type scan struct {
err error
bs []byte
}
func newScan(bs []byte, err error) *scan {
return &scan{bs: bs, err: err}
}
func (s *scan) Scan(model any) error {
if s.err != nil {
return s.err
}
return unmarshaler(s.bs, model)
}
type Cache interface {
Get(ctx context.Context, key string) ([]byte, error)
Gets(ctx context.Context, keys ...string) ([][]byte, error)
GetScan(ctx context.Context, key string) Scanner
GetEx(ctx context.Context, key string, duration time.Duration) ([]byte, error)
GetExScan(ctx context.Context, key string, duration time.Duration) Scanner
// Set value 会被序列化, 优先使用 MarshalBinary 方法, 没有则执行 json.Marshal
Set(ctx context.Context, key string, value any) error
Sets(ctx context.Context, vm map[string]any) error
// SetEx value 会被序列化, 优先使用 MarshalBinary 方法, 没有则执行 json.Marshal
SetEx(ctx context.Context, key string, value any, duration time.Duration) error
Del(ctx context.Context, keys ...string) error
GetDel(ctx context.Context, key string) ([]byte, error)
GetDelScan(ctx context.Context, key string) Scanner
Close()
}
var (
lock = &sync.Mutex{}
marshaler func(data any) ([]byte, error) = json.Marshal
unmarshaler func(data []byte, model any) error = json.Unmarshal
ErrorKeyNotFound = errors.New("key not found")
Default Cache
)
func handleValue(value any) ([]byte, error) {
var (
bs []byte
err error
)
switch value.(type) {
case []byte:
return value.([]byte), nil
}
if imp, ok := value.(encoded_value); ok {
bs, err = imp.MarshalBinary()
} else {
bs, err = marshaler(value)
}
return bs, err
}
func SetMarshaler(fn func(data any) ([]byte, error)) {
lock.Lock()
defer lock.Unlock()
marshaler = fn
}
func SetUnmarshaler(fn func(data []byte, model any) error) {
lock.Lock()
defer lock.Unlock()
unmarshaler = fn
}

61
database/cache/new.go vendored Normal file
View File

@ -0,0 +1,61 @@
package cache
import (
"context"
"fmt"
"gitea.loveuer.com/yizhisec/packages/tool"
"github.com/go-redis/redis/v8"
_ "github.com/go-redis/redis/v8"
"net/url"
)
var (
defaultRedis = "redis://127.0.0.1:6379"
)
func New(opts ...OptionFn) (Cache, error) {
var (
err error
cfg = &config{
ctx: context.Background(),
redis: &defaultRedis,
}
)
for _, opt := range opts {
opt(cfg)
}
if cfg.redis != nil {
var (
ins *url.URL
client *redis.Client
)
if ins, err = url.Parse(*cfg.redis); err != nil {
return nil, err
}
username := ins.User.Username()
password, _ := ins.User.Password()
client = redis.NewClient(&redis.Options{
Addr: ins.Host,
Username: username,
Password: password,
})
if err = client.Ping(tool.CtxTimeout(cfg.ctx, 5)).Err(); err != nil {
return nil, err
}
return newRedis(cfg.ctx, client), nil
}
return nil, fmt.Errorf("invalid cache config")
}
func Init(opts ...OptionFn) (err error) {
Default, err = New(opts...)
return err
}

39
database/cache/new_test.go vendored Normal file
View File

@ -0,0 +1,39 @@
package cache
import (
"testing"
)
func TestNew(t *testing.T) {
/* if err := Init(WithRedis("127.0.0.1", 6379, "", "MyPassw0rd")); err != nil {
t.Fatal(err)
}
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
if err := Default.Set(t.Context(), "zyp:haha", &User{
Name: "cache",
Age: 18,
}); err != nil {
t.Fatal(err)
}
s := Default.GetDelScan(t.Context(), "zyp:haha")
u := new(User)
if err := s.Scan(u); err != nil {
t.Fatal(err)
}
t.Logf("%#v", *u)
if err := Default.SetEx(t.Context(), "zyp:haha", &User{
Name: "redis",
Age: 2,
}, time.Hour); err != nil {
t.Fatal(err)
}*/
}

32
database/cache/option.go vendored Normal file
View File

@ -0,0 +1,32 @@
package cache
import (
"context"
"fmt"
)
type config struct {
ctx context.Context
redis *string
}
type OptionFn func(*config)
func WithCtx(ctx context.Context) OptionFn {
return func(c *config) {
if ctx != nil {
c.ctx = ctx
}
}
}
func WithRedis(host string, port int, username, password string) OptionFn {
return func(c *config) {
uri := fmt.Sprintf("%s:%d", host, port)
if username != "" || password != "" {
uri = fmt.Sprintf("redis://%s:%s@%s:%d", username, password, host, port)
}
c.redis = &uri
}
}

148
database/cache/redis.go vendored Normal file
View File

@ -0,0 +1,148 @@
package cache
import (
"context"
"errors"
"gitea.loveuer.com/yizhisec/packages/tool"
"github.com/go-redis/redis/v8"
"github.com/spf13/cast"
"sync"
"time"
)
var _ Cache = (*_redis)(nil)
type _redis struct {
sync.Mutex
ctx context.Context
client *redis.Client
}
func newRedis(ctx context.Context, client *redis.Client) *_redis {
r := &_redis{ctx: ctx, client: client}
go func() {
<-r.ctx.Done()
if client != nil {
r.Close()
}
}()
return r
}
func (r *_redis) GetDel(ctx context.Context, key string) ([]byte, error) {
s, err := r.client.GetDel(ctx, key).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
return nil, ErrorKeyNotFound
}
return nil, err
}
return tool.StringToBytes(s), nil
}
func (r *_redis) GetDelScan(ctx context.Context, key string) Scanner {
bs, err := r.GetDel(ctx, key)
return newScan(bs, err)
}
func (r *_redis) Get(ctx context.Context, key string) ([]byte, error) {
result, err := r.client.Get(ctx, key).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
return nil, ErrorKeyNotFound
}
return nil, err
}
return tool.StringToBytes(result), nil
}
func (r *_redis) Gets(ctx context.Context, keys ...string) ([][]byte, error) {
result, err := r.client.MGet(ctx, keys...).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
return nil, ErrorKeyNotFound
}
return nil, err
}
return tool.Map(
result,
func(item any, index int) []byte {
return tool.StringToBytes(cast.ToString(item))
},
), nil
}
func (r *_redis) GetScan(ctx context.Context, key string) Scanner {
return newScan(r.Get(ctx, key))
}
func (r *_redis) GetEx(ctx context.Context, key string, duration time.Duration) ([]byte, error) {
result, err := r.client.GetEx(ctx, key, duration).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
return nil, ErrorKeyNotFound
}
return nil, err
}
return tool.StringToBytes(result), nil
}
func (r *_redis) GetExScan(ctx context.Context, key string, duration time.Duration) Scanner {
return newScan(r.GetEx(ctx, key, duration))
}
func (r *_redis) Set(ctx context.Context, key string, value any) error {
bs, err := handleValue(value)
if err != nil {
return err
}
_, err = r.client.Set(ctx, key, bs, redis.KeepTTL).Result()
return err
}
func (r *_redis) Sets(ctx context.Context, values map[string]any) error {
vm := make(map[string]any)
for k, v := range values {
bs, err := handleValue(v)
if err != nil {
return err
}
vm[k] = bs
}
return r.client.MSet(ctx, vm).Err()
}
func (r *_redis) SetEx(ctx context.Context, key string, value any, duration time.Duration) error {
bs, err := handleValue(value)
if err != nil {
return err
}
_, err = r.client.SetEX(ctx, key, bs, duration).Result()
return err
}
func (r *_redis) Del(ctx context.Context, keys ...string) error {
return r.client.Del(ctx, keys...).Err()
}
func (r *_redis) Close() {
r.Lock()
defer r.Unlock()
_ = r.client.Close()
r.client = nil
}