乐趣区

关于springboot:springboot整合redis配置

依赖局部

<!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- spring2.X 集成 redis 所需 common-pool2-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.0</version>
        </dependency>

springboot2.0 版本默认应用 lettuce 连接池,默认不应用,只有在配置文件中应用连接池配置才开启,连接池须要依赖 commons-pools2 的依赖。

配置文件

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database= 0
#连贯超时工夫
spring.redis.timeout=1800000
#连接池最大连接数
spring.redis.lettuce.pool.max-active=20
#连接池最大阻塞连接时间,负值为无限度
spring.redis.lettuce.pool.max-wait=-1
#最大阻塞等待时间 (正数示意没限度)
spring.redis.lettuce.pool.max-idle=5
#最大闲暇线程数
spring.redis.lettuce.pool.min-idle=0

配置 RedisTemplate

@Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key 序列化形式
        template.setKeySerializer(redisSerializer);
        //value 序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap 序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }
退出移动版