Springboot2.x 集成Redis
程序员文章站
2022-07-07 11:27:08
...
Springboot2.x 集成Redis
Springboot1.5–>2.x 版本升级
具体可查看
Redis缓存变动
-
首先就是pom.xml导入依赖文件时由jedis
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>
变更为lettuce-core:
<dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> <version>5.0.4.RELEASE</version> <scope>compile</scope> </dependency>
- 具体到RedisCacheConfiguration配置类中,由Spingboot1.5的
@ConditionalOnBean(RedisTemplate.class)
变更为Springboot2.x的
@ConditionalOnClass(RedisConnectionFactory.class)
@ConditionalOnBean(RedisConnectionFactory.class)
- 因为1的原因 ,在RedisAutoConfigurationn中,将注解@ConditionalOnClass中的加在Jedis的部分删去了,取而代之的是用
@ConditionalOnClass(RedisOperations.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
代替,而RedisOperations.class 其实就是RedisTemplate(RedisTemplate/StringRedisTemplate)本身。
示例代码
@Bean(name = "userRedisTemplate")
public RedisTemplate<Object, User> userRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, User> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<User> userJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(User.class);
template.setDefaultSerializer(userJackson2JsonRedisSerializer);
return template;
}
@Bean
public RedisCacheManager userRedisCacheManager(RedisConnectionFactory redisConnectionFactory){
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory);
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer<>(User.class)));
RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config).build();
return cacheManager;
}