feat: optimize exists to check multiple keys in one call

* closes #32
This commit is contained in:
Mohamed Sohail 2024-10-04 12:19:26 +03:00
parent 55159196f4
commit 50870f10cf
Signed by: kamikazechaser
GPG Key ID: 7DD45520C01CD85D
4 changed files with 13 additions and 14 deletions

View File

@ -9,7 +9,7 @@ type (
Cache interface {
Add(context.Context, string) error
Remove(context.Context, string) error
Exists(context.Context, string) (bool, error)
Exists(context.Context, ...string) (bool, error)
Size(context.Context) (int64, error)
}

View File

@ -40,8 +40,8 @@ func (c *redisCache) Remove(ctx context.Context, key string) error {
return c.client.Do(ctx, cmd).Error()
}
func (c *redisCache) Exists(ctx context.Context, key string) (bool, error) {
cmd := c.client.B().Exists().Key(key).Build()
func (c *redisCache) Exists(ctx context.Context, key ...string) (bool, error) {
cmd := c.client.B().Exists().Key(key...).Build()
res, err := c.client.Do(ctx, cmd).AsBool()
if err != nil {
return false, err

View File

@ -26,9 +26,14 @@ func (c *mapCache) Remove(_ context.Context, key string) error {
return nil
}
func (c *mapCache) Exists(_ context.Context, key string) (bool, error) {
_, ok := c.xmap.Load(key)
return ok, nil
func (c *mapCache) Exists(_ context.Context, key ...string) (bool, error) {
for _, v := range key {
_, ok := c.xmap.Load(v)
if ok {
return true, nil
}
}
return false, nil
}
func (c *mapCache) Size(_ context.Context) (int64, error) {

View File

@ -147,16 +147,10 @@ func (hc *HandlerContainer) checkStables(ctx context.Context, from string, to st
return true, nil
}
// TODO: Pipeline this check on Redis with a new method
fromExists, err := hc.cache.Exists(ctx, from)
exists, err := hc.cache.Exists(ctx, from, to)
if err != nil {
return false, err
}
toExists, err := hc.cache.Exists(ctx, to)
if err != nil {
return false, err
}
return fromExists || toExists, nil
return exists, nil
}