Skip to content

Commit

Permalink
Merge pull request #345 from marklonquist/feature/redis-fix-remove-by…
Browse files Browse the repository at this point in the history
…-prefix

Fixes an issue where RemoveByPrefix does not remove data in redis if a KeyPrefix is set in DBConfig
  • Loading branch information
catcherwong authored Mar 9, 2022
2 parents 8b728b9 + d873108 commit fac1eed
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/EasyCaching.Redis/DefaultRedisCachingProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,11 @@ private RedisKey[] SearchRedisKeys(string pattern)
// from this redis dev specification, https://yq.aliyun.com/articles/531067 , maybe the appropriate scope is 100~500, using 200 here.
keys.AddRange(server.Keys(pattern: pattern, database: _cache.Database, pageSize: 200));

if (!string.IsNullOrWhiteSpace(_options.DBConfig.KeyPrefix))
keys = keys.Select(x => new RedisKey(
x.ToString().Remove(0, _options.DBConfig.KeyPrefix.Length)))
.ToList();

return keys.Distinct().ToArray();

//var keys = new HashSet<RedisKey>();
Expand Down Expand Up @@ -343,6 +348,9 @@ private string HandlePrefix(string prefix)
if (!prefix.EndsWith("*", StringComparison.OrdinalIgnoreCase))
prefix = string.Concat(prefix, "*");

if (!string.IsNullOrWhiteSpace(_options.DBConfig.KeyPrefix))
prefix = _options.DBConfig.KeyPrefix + prefix;

return prefix;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,5 +272,28 @@ public void KeyPrefixTest()
var val3 = WithKeyPrefix.Get<string>("KeyPrefix");
Assert.Equal(val1.Value, val3.Value);
}

[Fact]
public void RemoveByPrefixTest()
{
var WithKeyPrefix = _providerFactory.GetCachingProvider("WithKeyPrefix");

WithKeyPrefix.Set("KeyPrefix1", "ok", TimeSpan.FromSeconds(10));
WithKeyPrefix.Set("KeyPrefix2", "ok", TimeSpan.FromSeconds(10));

var val1 = WithKeyPrefix.Get<string>("KeyPrefix1");
var val2 = WithKeyPrefix.Get<string>("KeyPrefix2");

Assert.True(val1.HasValue);
Assert.True(val2.HasValue);
Assert.Equal(val1.Value, val2.Value);

WithKeyPrefix.RemoveByPrefix("Key");

var val3 = WithKeyPrefix.Get<string>("KeyPrefix1");
var val4 = WithKeyPrefix.Get<string>("KeyPrefix2");
Assert.False(val3.HasValue);
Assert.False(val4.HasValue);
}
}
}

0 comments on commit fac1eed

Please sign in to comment.