1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 00:22:41 +08:00
This commit is contained in:
2022-06-10 17:04:34 +08:00
parent 853b19fb02
commit 9bb232be93
22 changed files with 641 additions and 147 deletions

56
cache/cache.go vendored
View File

@ -1,36 +1,40 @@
package cache
import (
"context"
"errors"
"time"
"github.com/charlienet/go-mixed/bytesconv"
"github.com/charlienet/go-mixed/logx"
)
var ErrNotFound = errors.New("not found")
var ErrNotFound = errors.New("key not found")
type LoadFunc func() (any, error)
type LoadFunc func(context.Context) (any, error)
type Cache struct {
prefix string // 键前缀
retry int // 资源获取时的重试次数
mem MemCache // 内存缓存
distributdCache DistributdCache // 分布式缓存
publishSubscribe PublishSubscribe // 发布订阅
qps *qps
qps *qps //
logger logx.Logger // 日志记录
}
func NewCache(opts ...option) (*Cache, error) {
c := &Cache{
qps: NewQps(),
}
func NewCache(opts ...option) *Cache {
c := acquireDefaultCache()
for _, f := range opts {
f(c)
if err := f(c); err != nil {
return c
}
}
go c.subscribe()
return c, nil
return c
}
func (c *Cache) Set(key string, value any, expiration time.Duration) error {
@ -60,13 +64,16 @@ func (c *Cache) Get(key string, out any) error {
return nil
}
func (c *Cache) GetFn(key string, out any, fn LoadFunc, expiration time.Duration) (bool, error) {
ret, err := fn()
func (c *Cache) GetFn(ctx context.Context, key string, out any, fn LoadFunc, expiration time.Duration) (bool, error) {
c.Get(key, out)
// 多级缓存中未找到时,放置缓存对象
ret, err := fn(ctx)
if err != nil {
return false, err
}
_ = ret
c.Set(key, ret, expiration)
return false, nil
}
@ -75,20 +82,22 @@ func (c *Cache) Exist(key string) (bool, error) {
return false, nil
}
func (c *Cache) Delete(key string) error {
func (c *Cache) Delete(key ...string) error {
if c.mem != nil {
c.mem.Delete(key)
c.mem.Delete(key...)
}
if c.distributdCache != nil {
c.distributdCache.Delete(key)
c.distributdCache.Delete(key...)
}
return nil
}
func (c *Cache) getFromMem(key string, out any) error {
func (c *Cache) subscribe() {
}
func (c *Cache) getFromMem(key string, out any) error {
bytes, err := c.mem.Get(key)
if err != nil {
return err
@ -101,13 +110,16 @@ func (c *Cache) getFromMem(key string, out any) error {
return nil
}
func (c *Cache) subscribe() {
// 从缓存加载数据
func (c *Cache) getFromCache() {
}
func (c *Cache) genKey(key string) string {
if len(c.prefix) == 0 {
return key
}
// 从数据源加载数据
func (c *Cache) getFromSource(ctx context.Context, key string, fn LoadFunc) {
// 1. 尝试获取资源锁,如成功获取到锁加载数据
// 2. 未获取到锁,等待从缓存中获取
fn(ctx)
return c.prefix + "-" + key
}