Skip to content

Commit 8933f97

Browse files
committed
DATAREDIS-1032 - Polishing.
Add early return in cache key is a String. Convert convertCollectionLikeOrMapKey to non-nullable method by throwing an exception on a non-collection-like and Map-like type. Original pull request: #475.
1 parent 79ba1cc commit 8933f97

File tree

3 files changed

+29
-21
lines changed

3 files changed

+29
-21
lines changed

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

+13-7
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,10 @@ protected String createCacheKey(Object key) {
286286
*/
287287
protected String convertKey(Object key) {
288288

289+
if (key instanceof String) {
290+
return (String) key;
291+
}
292+
289293
TypeDescriptor source = TypeDescriptor.forObject(key);
290294

291295
if (conversionService.canConvert(source, TypeDescriptor.valueOf(String.class))) {
@@ -310,20 +314,21 @@ protected String convertKey(Object key) {
310314

311315
throw new IllegalStateException(String.format(
312316
"Cannot convert cache key %s to String. Please register a suitable Converter via 'RedisCacheConfiguration.configureKeyConverters(...)' or override '%s.toString()'.",
313-
source, key != null ? key.getClass().getSimpleName() : "Object"));
317+
source, key.getClass().getSimpleName()));
314318
}
315319

316-
@Nullable
317320
private String convertCollectionLikeOrMapKey(Object key, TypeDescriptor source) {
318321

319322
if (source.isMap()) {
320323

321-
String target = "{";
324+
StringBuilder target = new StringBuilder("{");
325+
322326
for (Entry<?, ?> entry : ((Map<?, ?>) key).entrySet()) {
323-
target += (convertKey(entry.getKey()) + "=" + convertKey(entry.getValue()));
327+
target.append(convertKey(entry.getKey())).append("=").append(convertKey(entry.getValue()));
324328
}
325-
target += "}";
326-
return target;
329+
target.append("}");
330+
331+
return target.toString();
327332
} else if (source.isCollection() || source.isArray()) {
328333

329334
StringJoiner sj = new StringJoiner(",");
@@ -336,7 +341,8 @@ private String convertCollectionLikeOrMapKey(Object key, TypeDescriptor source)
336341
}
337342
return "[" + sj.toString() + "]";
338343
}
339-
return null;
344+
345+
throw new IllegalArgumentException(String.format("Cannot convert cache key %s to String.", key));
340346
}
341347

342348
private boolean isCollectionLikeOrMap(TypeDescriptor source) {

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,7 @@ public ConversionService getConversionService() {
311311
*
312312
* @param cacheKeyConverter
313313
* @throws IllegalStateException if {@link #getConversionService()} does not allow converter registration.
314-
* @since 2.2
314+
* @since 2.1.11
315315
*/
316316
public void addCacheKeyConverter(Converter<?, String> cacheKeyConverter) {
317317
configureKeyConverters(it -> it.addConverter(cacheKeyConverter));
@@ -322,7 +322,7 @@ public void addCacheKeyConverter(Converter<?, String> cacheKeyConverter) {
322322
*
323323
* @param registryConsumer never {@literal null}.
324324
* @throws IllegalStateException if {@link #getConversionService()} does not allow converter registration.
325-
* @since 2.2
325+
* @since 2.1.11
326326
*/
327327
public void configureKeyConverters(Consumer<ConverterRegistry> registryConsumer) {
328328

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

+14-12
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424

2525
import java.io.Serializable;
2626
import java.nio.charset.Charset;
27+
import java.nio.charset.StandardCharsets;
2728
import java.util.Collection;
2829
import java.util.Collections;
2930
import java.util.Date;
@@ -57,7 +58,7 @@ public class RedisCacheTests {
5758

5859
String key = "key-1";
5960
String cacheKey = "cache::" + key;
60-
byte[] binaryCacheKey = cacheKey.getBytes(Charset.forName("UTF-8"));
61+
byte[] binaryCacheKey = cacheKey.getBytes(StandardCharsets.UTF_8);
6162

6263
Person sample = new Person("calmity", new Date());
6364
byte[] binarySample;
@@ -281,15 +282,15 @@ public void computePrefixCreatesCacheKeyCorrectly() {
281282

282283
doWithConnection(connection -> {
283284

284-
assertThat(connection.stringCommands().get("_cache_key-1".getBytes(Charset.forName("UTF-8"))))
285+
assertThat(connection.stringCommands().get("_cache_key-1".getBytes(StandardCharsets.UTF_8)))
285286
.isEqualTo(binarySample);
286287
});
287288
}
288289

289290
@Test // DATAREDIS-715
290291
public void fetchKeyWithComputedPrefixReturnsExpectedResult() {
291292

292-
doWithConnection(connection -> connection.set("_cache_key-1".getBytes(Charset.forName("UTF-8")), binarySample));
293+
doWithConnection(connection -> connection.set("_cache_key-1".getBytes(StandardCharsets.UTF_8), binarySample));
293294

294295
RedisCache cacheWithCustomPrefix = new RedisCache("cache", new DefaultRedisCacheWriter(connectionFactory),
295296
RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(SerializationPair.fromSerializer(serializer))
@@ -307,18 +308,19 @@ public void cacheShouldAllowListKeyCacheKeysOfSimpleTypes() {
307308
Object key = SimpleKeyGenerator.generateKey(Collections.singletonList("my-cache-key-in-a-list"));
308309
cache.put(key, sample);
309310

310-
Object target = cache.get(SimpleKeyGenerator.generateKey(Collections.singletonList("my-cache-key-in-a-list")));
311-
assertThat(((ValueWrapper) target).get()).isEqualTo(sample);
311+
ValueWrapper target = cache
312+
.get(SimpleKeyGenerator.generateKey(Collections.singletonList("my-cache-key-in-a-list")));
313+
assertThat(target.get()).isEqualTo(sample);
312314
}
313315

314316
@Test // DATAREDIS-1032
315317
public void cacheShouldAllowArrayKeyCacheKeysOfSimpleTypes() {
316318

317-
Object key = SimpleKeyGenerator.generateKey(new String[] { "my-cache-key-in-an-array" });
319+
Object key = SimpleKeyGenerator.generateKey("my-cache-key-in-an-array");
318320
cache.put(key, sample);
319321

320-
Object target = cache.get(SimpleKeyGenerator.generateKey(new String[] { "my-cache-key-in-an-array" }));
321-
assertThat(((ValueWrapper) target).get()).isEqualTo(sample);
322+
ValueWrapper target = cache.get(SimpleKeyGenerator.generateKey("my-cache-key-in-an-array"));
323+
assertThat(target.get()).isEqualTo(sample);
322324
}
323325

324326
@Test // DATAREDIS-1032
@@ -328,9 +330,9 @@ public void cacheShouldAllowListCacheKeysOfComplexTypes() {
328330
.generateKey(Collections.singletonList(new ComplexKey(sample.getFirstame(), sample.getBirthdate())));
329331
cache.put(key, sample);
330332

331-
Object target = cache.get(SimpleKeyGenerator
333+
ValueWrapper target = cache.get(SimpleKeyGenerator
332334
.generateKey(Collections.singletonList(new ComplexKey(sample.getFirstame(), sample.getBirthdate()))));
333-
assertThat(((ValueWrapper) target).get()).isEqualTo(sample);
335+
assertThat(target.get()).isEqualTo(sample);
334336
}
335337

336338
@Test // DATAREDIS-1032
@@ -340,9 +342,9 @@ public void cacheShouldAllowMapCacheKeys() {
340342
.generateKey(Collections.singletonMap("map-key", new ComplexKey(sample.getFirstame(), sample.getBirthdate())));
341343
cache.put(key, sample);
342344

343-
Object target = cache.get(SimpleKeyGenerator
345+
ValueWrapper target = cache.get(SimpleKeyGenerator
344346
.generateKey(Collections.singletonMap("map-key", new ComplexKey(sample.getFirstame(), sample.getBirthdate()))));
345-
assertThat(((ValueWrapper) target).get()).isEqualTo(sample);
347+
assertThat(target.get()).isEqualTo(sample);
346348
}
347349

348350
@Test // DATAREDIS-1032

0 commit comments

Comments
 (0)