diff --git a/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs b/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs index 50a9fb22..215d39e6 100644 --- a/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs +++ b/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs @@ -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(); @@ -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; } diff --git a/test/EasyCaching.UnitTests/CachingTests/RedisCachingProviderTest.cs b/test/EasyCaching.UnitTests/CachingTests/RedisCachingProviderTest.cs index 4c963a57..6fe66aef 100644 --- a/test/EasyCaching.UnitTests/CachingTests/RedisCachingProviderTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/RedisCachingProviderTest.cs @@ -272,5 +272,28 @@ public void KeyPrefixTest() var val3 = WithKeyPrefix.Get("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("KeyPrefix1"); + var val2 = WithKeyPrefix.Get("KeyPrefix2"); + + Assert.True(val1.HasValue); + Assert.True(val2.HasValue); + Assert.Equal(val1.Value, val2.Value); + + WithKeyPrefix.RemoveByPrefix("Key"); + + var val3 = WithKeyPrefix.Get("KeyPrefix1"); + var val4 = WithKeyPrefix.Get("KeyPrefix2"); + Assert.False(val3.HasValue); + Assert.False(val4.HasValue); + } } } \ No newline at end of file