在 Spring Data Redis 1.x 的时候,我们可能会在项目中编写这样一个 RedisConfig 类:
@Configuration
@EnableCaching
public class RedisConfig {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean(name = "redisTemplate")
public RedisTemplate initRedisTemplate() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
// 最大空闲数
poolConfig.setMaxIdle(50);
// 最大连接数
poolConfig.setMaxTotal(100);
// 最大等待毫秒数
poolConfig.setMaxWaitMillis(20000);
// 创建Jedis连接工厂
JedisConnectionFactory connectionFactory = new JedisConnectionFactory(poolConfig);
connectionFactory.setHostName("localhost");
connectionFactory.setPort(6379);
// 调用后初始化方法,没有它将抛出异常
connectionFactory.afterPropertiesSet();
// 自定义Redis序列化器
RedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
RedisSerializer stringRedisSerializer = new StringRedisSerializer();
// 定义RedisTemplate,并设置连接工程
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(connectionFactory);
// 设置序列化器
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setValueSerializer(jdkSerializationRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setHashValueSerializer(jdkSerializationRedisSerializer);
return redisTemplate;
}
@SuppressWarnings("rawtypes")
@Bean(name = "redisCacheManager")
public CacheManager initRedisCacheManager(@Autowired RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
// 设置超时时间为10分钟,单位为秒
cacheManager.setDefaultExpiration(600);
// 设置缓存名称
List<String> cacheNames = new ArrayList<>();
cacheNames.add("redisCacheManager");
cacheManager.setCacheNames(cacheNames);
return cacheManager;
}
}
但是在 Spring Data Redis 2.x 以后,我们继续这么编写可能会报如下错误: