springboot3.2 RedisCacheManager配置

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) {
       ...
    }
}

相关推荐

  1. springboot3.2 RedisCacheManager配置

    2024-07-20 22:32:01       25 阅读
  2. stm32 - 工程配置

    2024-07-20 22:32:01       49 阅读
  3. stm32 串口配置

    2024-07-20 22:32:01       42 阅读
  4. springboot-mongodb-连接配置

    2024-07-20 22:32:01       50 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-20 22:32:01       95 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-20 22:32:01       103 阅读
  3. 在Django里面运行非项目文件

    2024-07-20 22:32:01       84 阅读
  4. Python语言-面向对象

    2024-07-20 22:32:01       93 阅读

热门阅读

  1. springSecurity学习之springSecurity简介

    2024-07-20 22:32:01       26 阅读
  2. 分布式锁-redisson锁重试和WatchDog机制

    2024-07-20 22:32:01       19 阅读
  3. Photoshop图层类型

    2024-07-20 22:32:01       23 阅读
  4. (一)js前端开发中设计模式前篇之对象

    2024-07-20 22:32:01       24 阅读
  5. 网络安全-网络安全及其防护措施6

    2024-07-20 22:32:01       21 阅读
  6. [C++ 入门基础 - 命名空间]

    2024-07-20 22:32:01       20 阅读
  7. SharedPreferences 和 MMKV 是何方神圣

    2024-07-20 22:32:01       23 阅读
  8. 力扣1942.最小未被占据椅子的编号

    2024-07-20 22:32:01       22 阅读