perf(cache): should delete multiple keys at once to reduce operations in Redis cache (#6170)

This commit is contained in:
hulk 2024-10-12 22:25:18 +08:00 committed by GitHub
parent fa9e89bfe7
commit 291b3ba357
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 6 additions and 9 deletions

View File

@ -2,6 +2,7 @@ package redis
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"time" "time"
@ -47,7 +48,7 @@ func (c *cache) Store(cacheKey string, data []byte, ttl time.Duration) error {
func (c *cache) Retrieve(cacheKey string, allowExpired bool) ([]byte, status.RetrieveStatus, error) { func (c *cache) Retrieve(cacheKey string, allowExpired bool) ([]byte, status.RetrieveStatus, error) {
data, err := c.client.Get(context.Background(), cacheKey).Bytes() data, err := c.client.Get(context.Background(), cacheKey).Bytes()
if err != nil { if err != nil {
if err == redis.Nil { if errors.Is(err, redis.Nil) {
return nil, status.RetrieveStatusKeyMiss, nil return nil, status.RetrieveStatusKeyMiss, nil
} }
return nil, status.RetrieveStatusError, err return nil, status.RetrieveStatusError, err
@ -65,16 +66,13 @@ func (c *cache) SetTTL(cacheKey string, ttl time.Duration) {
// Remove removes the cache entry // Remove removes the cache entry
func (c *cache) Remove(cacheKey string) { func (c *cache) Remove(cacheKey string) {
err := c.client.Del(context.Background(), cacheKey).Err() c.BulkRemove([]string{cacheKey})
if err != nil {
zap.L().Error("error deleting cache key", zap.String("cacheKey", cacheKey), zap.Error(err))
}
} }
// BulkRemove removes the cache entries // BulkRemove removes the cache entries
func (c *cache) BulkRemove(cacheKeys []string) { func (c *cache) BulkRemove(cacheKeys []string) {
for _, cacheKey := range cacheKeys { if err := c.client.Del(context.Background(), cacheKeys...).Err(); err != nil {
c.Remove(cacheKey) zap.L().Error("error deleting cache keys", zap.Strings("cacheKeys", cacheKeys), zap.Error(err))
} }
} }

View File

@ -82,8 +82,7 @@ func TestBulkRemove(t *testing.T) {
mock.ExpectSet("key2", []byte("value2"), 10*time.Second).RedisNil() mock.ExpectSet("key2", []byte("value2"), 10*time.Second).RedisNil()
c.Store("key2", []byte("value2"), 10*time.Second) c.Store("key2", []byte("value2"), 10*time.Second)
mock.ExpectDel("key").RedisNil() mock.ExpectDel("key", "key2").RedisNil()
mock.ExpectDel("key2").RedisNil()
c.BulkRemove([]string{"key", "key2"}) c.BulkRemove([]string{"key", "key2"})
if err := mock.ExpectationsWereMet(); err != nil { if err := mock.ExpectationsWereMet(); err != nil {