2024-10-23 17:46:15 +08:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
|
2024-11-01 17:47:33 +08:00
|
|
|
"gitea.com/loveuer/gredis"
|
2024-10-23 17:46:15 +08:00
|
|
|
)
|
|
|
|
|
2024-11-01 17:47:33 +08:00
|
|
|
var _ Cache = (*_mem)(nil)
|
2024-10-23 17:46:15 +08:00
|
|
|
|
|
|
|
type _mem struct {
|
|
|
|
client *gredis.Gredis
|
|
|
|
}
|
|
|
|
|
2024-11-01 17:47:33 +08:00
|
|
|
func (m *_mem) GetScan(ctx context.Context, key string) Scanner {
|
2024-10-23 17:46:15 +08:00
|
|
|
return newScanner(m.Get(ctx, key))
|
|
|
|
}
|
|
|
|
|
2024-11-01 17:47:33 +08:00
|
|
|
func (m *_mem) GetExScan(ctx context.Context, key string, duration time.Duration) Scanner {
|
2024-10-23 17:46:15 +08:00
|
|
|
return newScanner(m.GetEx(ctx, key, duration))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *_mem) Get(ctx context.Context, key string) ([]byte, error) {
|
|
|
|
v, err := m.client.Get(key)
|
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, gredis.ErrKeyNotFound) {
|
|
|
|
return nil, ErrorKeyNotFound
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
bs, ok := v.([]byte)
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("invalid value type=%T", v)
|
|
|
|
}
|
|
|
|
|
|
|
|
return bs, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *_mem) GetEx(ctx context.Context, key string, duration time.Duration) ([]byte, error) {
|
|
|
|
v, err := m.client.GetEx(key, duration)
|
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, gredis.ErrKeyNotFound) {
|
|
|
|
return nil, ErrorKeyNotFound
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
bs, ok := v.([]byte)
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("invalid value type=%T", v)
|
|
|
|
}
|
|
|
|
|
|
|
|
return bs, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *_mem) Set(ctx context.Context, key string, value any) error {
|
|
|
|
bs, err := handleValue(value)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return m.client.Set(key, bs)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *_mem) SetEx(ctx context.Context, key string, value any, duration time.Duration) error {
|
|
|
|
bs, err := handleValue(value)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return m.client.SetEx(key, bs, duration)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *_mem) Del(ctx context.Context, keys ...string) error {
|
|
|
|
m.client.Delete(keys...)
|
|
|
|
return nil
|
|
|
|
}
|