Skip to content

Commit f65ea0b

Browse files
JosRoseboommp911de
authored andcommitted
Add support to clear cache by key pattern.
Closes #2379 Original pull request: #2380.
1 parent 7469ce0 commit f65ea0b

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/main/java/org/springframework/data/redis/cache/RedisCache.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
* @author Christoph Strobl
4646
* @author Mark Paluch
4747
* @author Piotr Mionskowski
48+
* @author Jos Roseboom
4849
* @see RedisCacheConfiguration
4950
* @see RedisCacheWriter
5051
* @since 2.0
@@ -174,8 +175,19 @@ public void evict(Object key) {
174175

175176
@Override
176177
public void clear() {
178+
clearByPattern("*");
179+
}
177180

178-
byte[] pattern = conversionService.convert(createCacheKey("*"), byte[].class);
181+
/**
182+
* <p>Clear keys that match the provided pattern.</p>
183+
* <br />
184+
* <p>Useful when the cache keys consists of multiple parameters. For example:
185+
* a cache key consists of a brand id and a country id. Now country 42 has relevant data updated. We want to clear all
186+
* the caches that involve country 42, regardless the brand. That can be done by clearByPattern("*42")</p>
187+
* @param keyPattern the pattern of the key
188+
*/
189+
public void clearByPattern(String keyPattern) {
190+
byte[] pattern = conversionService.convert(createCacheKey(keyPattern), byte[].class);
179191
cacheWriter.clean(name, pattern);
180192
}
181193

src/test/java/org/springframework/data/redis/cache/RedisCacheTests.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
* @author Christoph Strobl
6262
* @author Mark Paluch
6363
* @author Piotr Mionskowski
64+
* @author Jos Roseboom
6465
*/
6566
@MethodSource("testParams")
6667
public class RedisCacheTests {
@@ -108,6 +109,32 @@ void putShouldAddEntry() {
108109
});
109110
}
110111

112+
@ParameterizedRedisTest // GH-2379
113+
void cacheShouldBeClearedByPattern() {
114+
115+
cache.put(key, sample);
116+
117+
final String keyPattern = "*" + key.substring(1);
118+
cache.clearByPattern(keyPattern);
119+
120+
doWithConnection(connection -> {
121+
assertThat(connection.exists(binaryCacheKey)).isFalse();
122+
});
123+
}
124+
125+
@ParameterizedRedisTest // GH-2379
126+
void cacheShouldNotBeClearedIfNoPatternMatch() {
127+
128+
cache.put(key, sample);
129+
130+
final String keyPattern = "*" + key.substring(1) + "tail";
131+
cache.clearByPattern(keyPattern);
132+
133+
doWithConnection(connection -> {
134+
assertThat(connection.exists(binaryCacheKey)).isTrue();
135+
});
136+
}
137+
111138
@ParameterizedRedisTest // DATAREDIS-481
112139
void putNullShouldAddEntryForNullValue() {
113140

0 commit comments

Comments
 (0)