SpringBoot整合redis的總結及常見問題
阿新 • • 發佈:2018-12-14
1.需要引入spring-boot-starter-data-redis(Springboot1.5以上引用方式) 而不是 spring-boot-starter-redis(Springboot1.5以下引用方式)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.比較重要的包
cache:將redis用作快取
connection:各種連線方式及連線配置
serializer:系列化器,說白了就是存入redis資料庫的格式宣告,典型儲存方式是Jackson2JsonRedisSerializer
@Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>( Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); // 1 template.setKeySerializer(new StringRedisSerializer()); // 2 template.afterPropertiesSet(); return template; }
3.redis相關配置
spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=
spring.redis.database=1
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=500
spring.redis.pool.min-idle=0
spring.redis.timeout=5000
這些配置在字面上很好理解