1、启用并配置
添加 @EnableCaching 注解
并配置 RedisCacheManager
package config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.io.Serializable;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Properties;
@Configuration
@EnableCaching
public class RedisConfigure implements WebMvcConfigurer {
/**
* redis 序列化
* 否则redis会出现乱码或序列化失败
*/
@Bean
public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer<?> jackson2JsonRedisSerializer = defaultTypeSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
/**
* 设置缓存管理器
*/
@Bean
public RedisCacheManager getRedisCacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
//变双冒号为单冒号,和redisTemplate约定一致
.computePrefixWith(name -> name + ":")
.entryTtl(Duration.ofDays(7))
.disableCachingNullValues()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(defaultTypeSerializer()));
return RedisCacheManager.builder(factory)
.cacheDefaults(cacheConfiguration)
.transactionAware()
.build();
}
/**
* 自动转换的Jackson2JsonRedisSerializer
*/
Jackson2JsonRedisSerializer<Object> defaultTypeSerializer() {
// 1、配置 ObjectMapper
ObjectMapper objectMapper = JsonMapper.builder()
.visibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY)
.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY)
// 反序列化时对字段名的大小写不敏感
.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
// 默认使用 类上的注解来指导序列化和反序列化
.enable(MapperFeature.USE_ANNOTATIONS)
// 不存在的字段时,不会抛出异常
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
// 当找不解析类型(含子类),不会抛异常,继续尝试反序列化
.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false)
// 忽略序列化和反序列化的大小写
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
// 当找不到类型,会序列化成空对象
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.build(); // 创建ObjectMapper实例;
// 2.1 定义自定义的日期时间格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 2.2 创建模块并注册自定义的序列化器和反序列化器
SimpleModule module = new SimpleModule();
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
// 2.3 注册模块到 ObjectMapper
objectMapper.registerModule(module);
// 3 Jackson2JsonRedisSerializer
return new Jackson2JsonRedisSerializer<>(objectMapper, Object.class);
}
}
2 简单的使用
package service.impl;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author fisec
* @since 2024-04-24
*/
@Service
public class IpWhitelistServiceImpl extends ServiceImpl<IpWhitelistMapper, IpWhitelist> implements IIpWhitelistService {
//key 可选,一般是getId ,list一般量少使用
@Override
@Cacheable(value = RedisKeyConstants.IP_WHITE_LIST, key = "")
public List<IpWhitelist> getWhitelist() {
return this.list();
}
@Override
@CacheEvict(value = RedisKeyConstants.IP_WHITE_LIST, allEntries = true)
public void add(IpWhitelist ipWhitelist) {
...
}
@Override
@CacheEvict(value = RedisKeyConstants.IP_WHITE_LIST, allEntries = true)
public void delete(Long id) {
...
}
}