springboot2.0 与redis整合默认使用的是Lettuce,相较于jedis,lettuce 是一个可伸缩的,线程安全的redis客户端。在处理高并发方面有更多的优势。
RedisTemplate 使用
-
依赖, 主要需要的依赖为
compile('org.springframework.boot:spring-boot-starter-data-redis') compile('org.apache.commons:commons-pool2:2.6.0') compile('com.alibaba:fastjson:1.2.33')
-
yml 配置
spring: redis: database: 1 host: 192.168.1.XX port: 6379 lettuce: pool: max-active: 8 max-wait: -1ms min-idle: 0
-
redisTemplate 配置
@Configuration public class RedisConfiguration { @Bean public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory connectionFactory){ RedisTemplate template = new RedisTemplate(); template.setConnectionFactory(connectionFactory); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); template.setValueSerializer(jackson2JsonRedisSerializer); template.setKeySerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } }
-
使用
@Autowired RedisTemplate redisTemplate; public void addData(){ MyInfo myInfo = new MyInfo("11","22","s344"); redisTemplate.opsForValue().set("11",myInfo); redisTemplate.opsForValue().set("myse","mys"); }
spring-cache 与 redis 整合
spring cache 可以在不更改现有代码逻辑的基础上,通过增加注解的方式,实现缓存。 减少代码侵入
在gradle文件中增加 spring-cache的相关依赖
compile('org.springframework.boot:spring-boot-starter-cache')
配置CacheManager, 在Configuration 配置类上增加EnableCache 注解;
-
配置CacheManager Bean,代码为
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); cacheConfiguration = cacheConfiguration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)); cacheConfiguration.entryTtl(Duration.ofMinutes(10)); CacheManager cacheManager = new RedisCacheManager(redisCacheWriter, cacheConfiguration); return cacheManager;
完成上述配置后,便可以在service中直接使用spring-cache注解,完整代码地址: 代码