spring使用Redis自定義字首字尾名(去掉SimpleKey []+自定義)
阿新 • • 發佈:2018-12-28
spring中自動加上 SimpleKey [] 解決方案
一、自定義字尾名
1、定義類實現KeyGenerator介面
MyKeyGenerator
package com.wbg.springRedis.service.impl; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.stereotype.Component; import java.lang.reflect.Method; @Component("myKeyGenerator")public class MyKeyGenerator implements KeyGenerator { @Override public Object generate(Object target, Method method, Object... params) { //返回字尾名 //return method.getName(); //注意,這裡不能返回null,否則會報錯 //java.lang.IllegalArgumentException: // Null key returned for cache operation (maybe you are using named params on classes without debug info?) Builder[public java.util.List com.wbg.springRedis.service.impl.RoleServiceImpl.listAll()] caches=[listAll] | key='' | keyGenerator='myKeyGenerator' | cacheManager='' | cacheResolver='' | condition='' | unless='' | sync='false'return ""; } }
2、註解使用:
@Cacheable(value = "listAll", keyGenerator = "myKeyGenerator")
已經解決
二、自定義字首:
@Bean RedisCacheManager cacheManager() { RedisCacheConfiguration configuration = RedisCacheConfiguration .defaultCacheConfig() .computePrefixWith(cacheName-> "redis" + cacheName) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string())) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.java())); return RedisCacheManager.builder(redisConnectionFactory()).cacheDefaults(configuration).build(); }