Skip to content

Commit fac1eed

Browse files
authored
Merge pull request #345 from marklonquist/feature/redis-fix-remove-by-prefix
Fixes an issue where RemoveByPrefix does not remove data in redis if a KeyPrefix is set in DBConfig
2 parents 8b728b9 + d873108 commit fac1eed

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/EasyCaching.Redis/DefaultRedisCachingProvider.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,11 @@ private RedisKey[] SearchRedisKeys(string pattern)
304304
// from this redis dev specification, https://yq.aliyun.com/articles/531067 , maybe the appropriate scope is 100~500, using 200 here.
305305
keys.AddRange(server.Keys(pattern: pattern, database: _cache.Database, pageSize: 200));
306306

307+
if (!string.IsNullOrWhiteSpace(_options.DBConfig.KeyPrefix))
308+
keys = keys.Select(x => new RedisKey(
309+
x.ToString().Remove(0, _options.DBConfig.KeyPrefix.Length)))
310+
.ToList();
311+
307312
return keys.Distinct().ToArray();
308313

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

351+
if (!string.IsNullOrWhiteSpace(_options.DBConfig.KeyPrefix))
352+
prefix = _options.DBConfig.KeyPrefix + prefix;
353+
346354
return prefix;
347355
}
348356

test/EasyCaching.UnitTests/CachingTests/RedisCachingProviderTest.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,5 +272,28 @@ public void KeyPrefixTest()
272272
var val3 = WithKeyPrefix.Get<string>("KeyPrefix");
273273
Assert.Equal(val1.Value, val3.Value);
274274
}
275+
276+
[Fact]
277+
public void RemoveByPrefixTest()
278+
{
279+
var WithKeyPrefix = _providerFactory.GetCachingProvider("WithKeyPrefix");
280+
281+
WithKeyPrefix.Set("KeyPrefix1", "ok", TimeSpan.FromSeconds(10));
282+
WithKeyPrefix.Set("KeyPrefix2", "ok", TimeSpan.FromSeconds(10));
283+
284+
var val1 = WithKeyPrefix.Get<string>("KeyPrefix1");
285+
var val2 = WithKeyPrefix.Get<string>("KeyPrefix2");
286+
287+
Assert.True(val1.HasValue);
288+
Assert.True(val2.HasValue);
289+
Assert.Equal(val1.Value, val2.Value);
290+
291+
WithKeyPrefix.RemoveByPrefix("Key");
292+
293+
var val3 = WithKeyPrefix.Get<string>("KeyPrefix1");
294+
var val4 = WithKeyPrefix.Get<string>("KeyPrefix2");
295+
Assert.False(val3.HasValue);
296+
Assert.False(val4.HasValue);
297+
}
275298
}
276299
}

0 commit comments

Comments
 (0)