Skip to content

Commit

Permalink
增加缓存前缀
Browse files Browse the repository at this point in the history
  • Loading branch information
limingxinleo committed Dec 16, 2024
1 parent e9db70b commit bb7a907
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
12 changes: 9 additions & 3 deletions cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,15 @@ type PackerInterface interface {
type Cache[T any] struct {
Driver DriverInterface
Packer PackerInterface
Prefix string
}

func (c *Cache[T]) Key(key string) string {
return c.Prefix + key
}

func (c *Cache[T]) Get(key string, defaultValue T) error {
res, err := c.Driver.Get(key)
res, err := c.Driver.Get(c.Key(key))
if err != nil {
return err
}
Expand All @@ -42,7 +47,7 @@ func (c *Cache[T]) Get(key string, defaultValue T) error {
}

func (c *Cache[T]) Has(key string) (bool, error) {
return c.Driver.Has(key)
return c.Driver.Has(c.Key(key))
}

func (c *Cache[T]) Set(key string, value T, seconds int) error {
Expand All @@ -51,10 +56,11 @@ func (c *Cache[T]) Set(key string, value T, seconds int) error {
return err
}

return c.Driver.Set(key, res, seconds)
return c.Driver.Set(c.Key(key), res, seconds)
}

func (c *Cache[T]) Run(key string, defaultValue T, seconds int, fn func(T) error) error {
key = c.Key(key)
err := c.Get(key, defaultValue)
if err != nil && !errors.Is(err, error_code.NotFound) {
return err
Expand Down
4 changes: 2 additions & 2 deletions cache/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ func TestCache_Run(t *testing.T) {
Type: "node",
}))

fooCache := &Cache[*Foo]{Driver: driver, Packer: &JsonPacker{}}
key := "c2:" + strconv.FormatInt(time.Now().Unix(), 10)
fooCache := &Cache[*Foo]{Driver: driver, Packer: &JsonPacker{}, Prefix: "c2:"}
key := strconv.FormatInt(time.Now().Unix(), 10)

var result Foo
_ = fooCache.Run(key, &result, 60, func(foo *Foo) error {
Expand Down

0 comments on commit bb7a907

Please sign in to comment.