File tree Expand file tree Collapse file tree 2 files changed +40
-1
lines changed
main/java/org/springframework/data/redis/cache
test/java/org/springframework/data/redis/cache Expand file tree Collapse file tree 2 files changed +40
-1
lines changed Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 6161 * @author Christoph Strobl
6262 * @author Mark Paluch
6363 * @author Piotr Mionskowski
64+ * @author Jos Roseboom
6465 */
6566@ MethodSource ("testParams" )
6667public 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
You can’t perform that action at this time.
0 commit comments