Springboot2.x 集成Redis

Springboot2.x 集成Redis

Springboot1.5–>2.x 版本升级

具体可查看

Redis缓存变动

  1. 首先就是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>									
    

Redis 的三个框架

  1. 具体到RedisCacheConfiguration配置类中,由Spingboot1.5的
@ConditionalOnBean(RedisTemplate.class)

​ 变更为Springboot2.x的

@ConditionalOnClass(RedisConnectionFactory.class)
@ConditionalOnBean(RedisConnectionFactory.class)
  1. 因为1的原因 ,在RedisAutoConfigurationn中,将注解@ConditionalOnClass中的加在Jedis的部分删去了,取而代之的是用
@ConditionalOnClass(RedisOperations.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })

代替,而RedisOperations.class 其实就是RedisTemplate(RedisTemplate/StringRedisTemplate)本身。

示例代码

@Configuration
public class RedisConf {
    @Bean
    public RedisTemplate<Object, User> userRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, User> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<User> userJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<User>(User.class);
        template.setDefaultSerializer(userJackson2JsonRedisSerializer);
        return template;
    }
    @Bean
    public RedisCacheManager userRedisCacheManager(RedisConnectionFactory redisConnectionFactory){
        RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
                .builder(redisConnectionFactory);
        return builder.build();
    }
}

Github

demo

你可能感兴趣的:(杂论)