springboot2.0 與redis整合默認使用的是Lettuce,相較於jedis,lettuce 是一個可伸縮的,線程安全的redis客戶端。在處理高併發方面有更多的優點。java
依賴, 主要須要的依賴爲git
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 配置github
spring: redis: database: 1 host: 192.168.1.XX port: 6379 lettuce: pool: max-active: 8 max-wait: -1ms min-idle: 0
redisTemplate 配置redis
@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; } }
1. 使用
@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 能夠在不更改現有代碼邏輯的基礎上,經過增長註解的方式,實現緩存。 減小代碼侵入spring
compile('org.springframework.boot:spring-boot-starter-cache')
配置CacheManager Bean,代碼爲apache
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註解,完整代碼: 代碼json