自定义SpringCache For Redis配置

2022-06-28 20:24:37 733

SpringCache抽象了缓存使用场景, 对外提供注解, 无需繁琐配置即可获得缓存能力

默认支持一堆缓存中间件, 其中就包括Redis

在此仅提供一种缓存配置的思路

@Data
@Component
@ConfigurationProperties(prefix = "spring.cache.redis")
public class RedisCacheProperties {

    /**
     * 区分于业务使用的Redis库
     *
     * 独立SpringCache的数据
     *
     * 也可以改动配置使用另外的Redis
     */
    private Integer database;

}



@Configuration(proxyBeanMethods = false)
public class RedisCacheConfig {

    private static final String KEY_SEPARATOR = "::";
    
    //定义缓存的序列化方式
    @Bean("objectMapperForRedisSerializer")
    public ObjectMapper objectMapperForRedisSerializer(JavaTimeModule javaTimeModule) {
        var om = new ObjectMapper();
        om.registerModule(new SimpleModule().addSerializer(new NullValueSerializer(null)));
        om.registerModule(javaTimeModule);
        om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.EVERYTHING,
                JsonTypeInfo.As.PROPERTY);
        return om;
    }


    @Bean("redisConnectionFactoryForSpringCache")
    public LettuceConnectionFactoryWrapper redisConnectionFactoryForSpringCache(
            LettuceConnectionFactory redisConnectionFactory, RedisCacheProperties redisCacheProperties) {

        RedisStandaloneConfiguration standaloneConfiguration = redisConnectionFactory.getStandaloneConfiguration();

        RedisStandaloneConfiguration standaloneConfigurationNew = new RedisStandaloneConfiguration();

        BeanUtil.copyProperties(standaloneConfiguration, standaloneConfigurationNew,
                CopyOptions.create().setIgnoreNullValue(true));

        standaloneConfigurationNew.setDatabase(redisCacheProperties.getDatabase());

        LettuceConnectionFactory lettuceConnectionFactoryNew = new LettuceConnectionFactory(standaloneConfigurationNew);

        BeanUtil.copyProperties(redisConnectionFactory, lettuceConnectionFactoryNew, CopyOptions.create()
                .setIgnoreNullValue(true).setIgnoreProperties("standaloneConfig", "configuration"));

        lettuceConnectionFactoryNew.setDatabase(redisCacheProperties.getDatabase());
        lettuceConnectionFactoryNew.afterPropertiesSet();

        return LettuceConnectionFactoryWrapper.build(lettuceConnectionFactoryNew);
    }


    @Bean
    public CachingConfigurer cachingConfigurer(CacheProperties cacheProperties,
                                               ObjectProvider<CacheManagerCustomizer<?>> customizers,
                                               ObjectProvider<RedisCacheConfiguration> redisCacheConfiguration,
                                               ObjectProvider<RedisCacheManagerBuilderCustomizer> builderCustomizers,
                                               LettuceConnectionFactoryWrapper redisConnectionFactoryWrapper,
                                               @Qualifier("objectMapperForRedisSerializer") ObjectMapper om) {

        RedisCacheManager cacheManager = buildCacheManager(cacheProperties, customizers, redisCacheConfiguration,
                builderCustomizers, redisConnectionFactoryWrapper.getLettuceConnectionFactory(), om);

        KeyGenerator keyGenerator = buildKeyGenerator();

        IgnoreExceptionCacheErrorHandler errorHandler = new IgnoreExceptionCacheErrorHandler();


        return new CachingConfigurer() {
            @Override
            public CacheManager cacheManager() {
                return cacheManager;
            }

            @Override
            public KeyGenerator keyGenerator() {
                return keyGenerator;
            }

            @Override
            public CacheErrorHandler errorHandler() {
                return errorHandler;
            }
        };
    }


    /**
     * 自定义Redis Key生成策略
     */
    public KeyGenerator buildKeyGenerator() {
        return (target, method, params) -> {
            var builder = new StringBuilder();
            for (var param : params) {
                builder.append(param).append(KEY_SEPARATOR);
            }

            builder.append(target.getClass().getName()).append(KEY_SEPARATOR);
            builder.append(method.getName());

            return builder.toString();
        };
    }


    RedisCacheManager buildCacheManager(CacheProperties cacheProperties,
                                        ObjectProvider<CacheManagerCustomizer<?>> customizers,
                                        ObjectProvider<RedisCacheConfiguration> redisCacheConfiguration,
                                        ObjectProvider<RedisCacheManagerBuilderCustomizer> redisCacheManagerBuilderCustomizers,
                                        LettuceConnectionFactory redisConnectionFactory,
                                        ObjectMapper om) {

        RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(determineConfiguration(cacheProperties, om, redisCacheConfiguration));

        List<String> cacheNames = cacheProperties.getCacheNames();
        if (!cacheNames.isEmpty()) {
            builder.initialCacheNames(new LinkedHashSet<>(cacheNames));
        }
        if (cacheProperties.getRedis().isEnableStatistics()) {
            builder.enableStatistics();
        }

        redisCacheManagerBuilderCustomizers.orderedStream().forEach(customizer -> customizer.customize(builder));

        return new CacheManagerCustomizers(customizers.orderedStream().toList()).customize(builder.build());
    }

    private RedisCacheConfiguration determineConfiguration(
            CacheProperties redisCacheProperties,
            ObjectMapper om,
            ObjectProvider<RedisCacheConfiguration> redisCacheConfiguration) {

        return redisCacheConfiguration.getIfAvailable(() -> createConfiguration(redisCacheProperties, om));
    }


    private RedisCacheConfiguration createConfiguration(CacheProperties cacheProperties, ObjectMapper om) {

        CacheProperties.Redis redisProperties = cacheProperties.getRedis();

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

        config = config.serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer(om)));
        config = config.serializeKeysWith(SerializationPair.fromSerializer(new StringRedisSerializer()));

        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }


    @Slf4j
    static class IgnoreExceptionCacheErrorHandler implements CacheErrorHandler {

        @Override
        public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
            log.error("cacheGetError, key: {}", key, exception);
        }

        @Override
        public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
            log.error("cachePutError, key: {}", key, exception);
        }

        @Override
        public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
            log.error("cacheEvictError, key: {}", key, exception);
        }

        @Override
        public void handleCacheClearError(RuntimeException exception, Cache cache) {
            log.error("cacheClearError", exception);
        }
    }

    @Data
    static class LettuceConnectionFactoryWrapper {
        private LettuceConnectionFactory lettuceConnectionFactory;

        public static LettuceConnectionFactoryWrapper build(LettuceConnectionFactory lettuceConnectionFactory) {
            LettuceConnectionFactoryWrapper wrapper = new LettuceConnectionFactoryWrapper();
            wrapper.lettuceConnectionFactory = lettuceConnectionFactory;
            return wrapper;
        }
    }

对应配置文件

spring:
  redis:
    client-type: lettuce
    database: 0
    host: 192.168.101.128
    port: 6379
    password: 123456
  cache:
    redis:
      time-to-live: 10m
      database: 1


自定义rocketmq-spring-boot-starter

一般使用rocketmq-starter都会进行不同程度的封装, 在此分享一种封装思路基于rocketmq-spring-boot-starter <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rock
2022-09-26

Java类加载器机制及应用

0x00 何时触发类加载动作显式加载通过ClassLoader的loadClass方法通过ClassLoader的findClass方法通过Class.forName隐式加载遇到new、getstatic、putstatic、invokestatic这4条字节码指令时对类进行反射调用时当初始化一个类
2022-08-08

MyBatis-Plus动态返回实体类

1. 自定义SqlSession@Slf4j public class GenericSqlSession extends DefaultSqlSession { private static final ThreadLocal<Class<?>> CTX = new ThreadLoca
2022-07-18

自定义SpringCache For Redis配置

SpringCache抽象了缓存使用场景, 对外提供注解, 无需繁琐配置即可获得缓存能力默认支持一堆缓存中间件, 其中就包括Redis在此仅提供一种缓存配置的思路 @Data @Component @ConfigurationProperties(prefix = "spring.cache.red
2022-06-28

SpringBoot自定义枚举序列化方式

在平常web开发中, 或多或少的会使用到枚举类型但是springboot对枚举的序列化并不太符合实际开发需求比如public enum MerchantStatusEnum { NORMAL(100, "正常"), BAN(200, "封禁"); private fina
2022-06-22

SpringBoot LocalDateTime序列化配置

项目中用LocalDateTime替换Date后, 许多地方需要增加配置配置Json响应格式化方式注册JavaTimeModule/** * 序列化LocalDateTime */ @Bean public JavaTimeModule javaTimeModule() { JavaTi
2022-05-25

OpenFeign统一Fallback处理

@Slf4j @Configuration(proxyBeanMethods = false) public class FeignLoadBalancedConfiguration { @Bean public LoadBalancerFeignClient feignClie
2022-04-20

SpringBoot读写分离配置与事务

引入依赖<dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.5.1</version>
2022-03-29

SpringBoot加载外部配置文件的几种方式

一@PropertySource("file:F:/my.properties") @Configuration @ConfigurationProperties(prefix = "my") public class TestConfig { private String url;
2021-12-02

SpringBoot加载自定义yml文件

官方推荐使用yml,却不支持自定义的yml,匪夷所思。package com.xxx.xxx.xxx; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; i
2024-10-23

SpringBoot线程池+多线程

启动类上加注解 @SpringBootApplication @EnableAsync public class SpringApplication { public static void main(String[] args) { SpringApplication.r
2020-07-16
编写自己的Spring Boot Starter

编写自己的Spring Boot Starter

1.新建一个maven项目命名规则统一是xxx-spring-boot-starter完整pom.xml<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"
2020-06-29
解决SpringBoot+JPA中使用set方法时自动更新数据库问题

解决SpringBoot+JPA中使用set方法时自动更新数据库问题

首先引入EntityManager:然后用它来强转获得HibernateEntityManager,然后调用获得Session,然后在set完之后用Session的.evict()方法清掉该对象缓存(并非所有对象缓存),如此就ok了...好吧,已经java11不建议用了,不过还能用,先用着吧!更新了
2020-04-04

SpringBoot Undertow http跳转https

package com.mtons.mblog.config; import io.undertow.Undertow; import io.undertow.UndertowOptions; import io.undertow.servlet.api.SecurityConstraint; i
2020-03-28

SpringBoot 启动普通java工程

引入依赖<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.0.9</version> </dependency>
2020-03-28

freemarker 时间显示不正常 设置时区

项目在本地开发的时候显示正常,部署上服务器就一直差8个小时,最后发现freemarker官方文档有这样的说明time_zone:时区的名称来显示并格式化时间。 默认情况下,使用JVM的时区。 也可以是 Java 时区 API 接受的值,或者 "JVM default" (从 FreeMarker 2
2020-03-28
IDEA 2019.1 xml 不高亮

IDEA 2019.1 xml 不高亮

前几天更新了idea后,发现xml里的代码都没有了高亮,变得跟记事本一个德性了打开setting ,搜索 File Types,找到xml项, 查看下方的匹配格式,果然没有xml,(idea真是厉害)点击右方的+,输入*.xml,点击ok,解决问题
2020-03-28

npm install 淘宝镜像

npm install --registry=https://registry.npm.taobao.org
2020-03-28
Java中方法的参数传递机制

Java中方法的参数传递机制

来看一段代码 public class Man { private String name; private Integer age; public String getName() { return name; } publi
2020-03-28
基于自定义注解手写权限控制

基于自定义注解手写权限控制

方法一: AOP 方法二: 拦截器项目结构项目依赖<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-w
2020-03-28

Docker 部署 详细全过程 附代码

Docker 部署本站 全过程环境:CentOS7.61. 安装Docker其他版本CentOS可以参考这个https://help.aliyun.com/document_detail/187598.html查看本机内核版本,内核版本需高于 3.10uname -r 确保 yum 包最新yum u
2020-03-28

SpringBoot 启动普通java工程

引入依赖<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.0.9</version> </dependency>
2020-03-28

Vue.js DOM操作

<template> <input type="button" @click="reply($event)" value="回复"> </template> export default { methods: { replyFun(e) {
2020-03-29
CentOS7编译调试OpenJDK12

CentOS7编译调试OpenJDK12

1. 下载源码https://hg.openjdk.java.net/jdk/jdk12点击左侧的browse,再点击zip,就可以下载zip格式的源码压缩包。unzip xxx.zip 解压文件2. 安装jdkyum install java-11-openjdk-devel -y3. 运行con
2020-04-23
编写自己的Spring Boot Starter

编写自己的Spring Boot Starter

1.新建一个maven项目命名规则统一是xxx-spring-boot-starter完整pom.xml<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"
2020-06-29