# 1.Spring Data Redis (Access+Driver)
Spring Data Redis 是属于 Spring Data 下的一个模块,作用就是简化对于 redis 的操做。
SpringBoot2.x后RedisTemplate采用是lettuce(基于netty采用异步非阻塞式lO)进行通信,大并发下比 jedis 效率更高。
RedisTemplate模板使用序列化器操作redis数据,预定义的序列化方案有:
序列化器 | 说明 |
---|---|
JdkSerializationRedisSerializer | POJO对象的存取场景,使用JDK本身序列化机制,将pojo类通过ObjectInputstream/ObjectOutputstream进行序列化操作,最终redis-server中将存储字节序列。是目前最常用的序列化策略。 |
stringRedisSerializer | Key或者value为字符串的场景,根据指定的charset对数据的字节序列编码成string,是"new String(bytes,charset)"和“string.getBytes(charset)"的直接封装。是最轻量级和高效的策略。 |
GenericJackson2JsonRedisSerializer | jackson-json工具提供了javabean与json之间的转换能力,可以将pojo实例序列化成json格式存储在redis中,也可以将json格式的数据转换成pojo实例。 |
<!-- Spring Data Redis的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
# 序列化配置:
@Slf4j
@Configuration
public class RedisConfig {
//RedisTemplate 序列化配置
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory, ObjectMapper objectMapper) {
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setStringSerializer(new StringRedisSerializer());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
//注解方式redis序列化方式配置
@Bean
@Primary
public GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer() {
ObjectMapper mapper = new ObjectMapper();
//解决查询缓存转换异常的问题
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//支持JDK 1.8 日期 --start
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
.registerModule(new ParameterNamesModule());
//支持JDK 1.8 日期 --end
return new GenericJackson2JsonRedisSerializer(mapper);
}
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory, GenericJackson2JsonRedisSerializer serializer) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
//配置缓存时长
.entryTtl(Duration.ofMinutes(30))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer));
RedisCacheManager build = RedisCacheManager.builder(factory)
.cacheDefaults(redisCacheConfiguration)
.build();
return build;
}
//自定义key生成策略
@Bean
@Primary
public KeyGenerator keyGenerator() {
return (target, method, params) -> {
StringBuilder append = new StringBuilder()
.append(target.getClass().getName()).append(":")
.append(method.getName()).append(":");
for (Object param : params) {
try {
append.append(new ObjectMapper().writeValueAsString(param)).append(":");
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
log.info(append.toString());
String key = DigestUtils.md5DigestAsHex(append.toString().getBytes(StandardCharsets.UTF_8));
log.info(key);
return key;
};
}
}
# 使用:
Spring Cache 注解形式
@EnableCaching //开启注解 @SpringBootApplication public class SpringDataRedisApplication { public static void main(String[] args) { SpringApplication.run(SpringDataRedisApplication.class, args); } }
//以users:id为key,查询redis,有就从缓存返回,没有就执行代码逻辑 @Cacheable(value = "users", key = "#id") public User getUserById(Long id) { // 从数据库中获取用户信息 } //执行代码逻辑,并将结果保存至缓存。此注解并不会查询缓存 @CachePut(value = "users", key = "#user.id") public User saveUser(User user) { // 将用户信息保存到数据库 } //删除数据,并清空缓存 @CacheEvict(value = "users", key = "#id") public void deleteUserById(Long id) { // 从数据库中删除用户信息 }
RedisTemplate 形式
redisTemplate.opsForValue():操作字符串 redisTemplate.opsForHash():操作hash redisTemplate.opsForList():操作list redisTemplate.opsForSet():操作set redisTemplate.opsForZSet():操作zset