spring使用Redis自定义前缀后缀名(去掉SimpleKey []+自定义)
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(); }