SpringBoot集成Ehcache、Redis示例

本文介绍了Spring中Ehcache和Redis的集成方式,包括依赖配置、缓存管理器的实现以及关键配置。对于Ehcache,详细讲解了配置文件ehcache.xml的内容以及属性注解。对于Redis,提到了原生Spring Cache不支持缓存过期,需要自定义缓存过期时间,并展示了如何通过CustomizerRedisCacheManager进行配置。
摘要由CSDN通过智能技术生成

一、摘要

        1.1、Spring3.1开始内置了五个缓存管理器实现,如下所示:

  • SimpleCacheManager
  • NoOpCacheManager
  • ConcurrentMapCacheManager
  • CompositeCacheManager
  • EhcacheCacheManager

        1.2、Spring3.2引入了另外一个缓存管理器,这个管理器可以用在基于Jcache(JSR-107)的缓存供应商之中。除了核心的spring框架,spring data又提供了两个缓存管理器。

  • RedisCacheManager
  • GemfireCacheManager

JSR是Java Specification Requests的缩写,意思是Java 规范提案。是指向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求。任何人都可以提交JSR,以向Java平台增添新的API和服务。JSR已成为Java界的一个重要标准。

今天我们要讲的是Srping目前集成使用比较广泛的Ehcache和Redis集成方式。

二、集成Ehcache

主要依赖包是spring-boot-starter-cache和ehcache,如下:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.0</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-cache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-cache</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>2021.0.0-RC1</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- mybatis plus 代码生成器 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.71</version>
        </dependency>

        <!--spring的集成缓存框架的jar-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <!--spring要集成的ehcache缓存jar-->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>

    </dependencies>

 resources目录下配置ehcache.xml配置文件():

<?xml version="1.0" encoding="UTF-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../../../../../../ehcache.xsd">

    <!-- 磁盘缓存位置 -->
    <diskStore path="java.io.tmpdir"/>
    <!--defaultCache:echcache 的默认缓存策略 -->
<!--    <defaultCache-->
<!--            maxElementsInMemory="10000"-->
<!--            eternal="false"-->
<!--            timeToIdleSeconds="300"-->
<!--            timeToLiveSeconds="300"-->
<!--            maxElementsOnDisk="10000000"-->
<!--            diskExpiryThreadIntervalSeconds="300"-->
<!--            memoryStoreEvictionPolicy="LRU">-->
<!--        <persistence strategy="localTempSwap"/>-->
<!--    </defaultCache>-->
    <!-- 根据id查询博客方法 -->
    <cache name="blog:queryById"
           maxElementsInMemory="30"
           eternal="false"
           timeToIdleSeconds="30"
           timeToLiveSeconds="30"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="300"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>

</ehcache>

ehcache属性注解:
1、name:缓存名称。
2、maxElementsInMemory:缓存最大个数。
3、eternal:对象是否永久有效,一但设置了,timeout将不起作用。
4、timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
5、timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
6、overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
7、diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
8、maxElementsOnDisk:硬盘最大缓存个数。
9、diskPersistent:是否缓存虚拟机重启期数据(Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
10、diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
11、memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
12、clearOnFlush:内存数量最大时是否清除。
 

 ehcache管理器的实现:

@Component
public class EhCacheManager {

    /**
     * ehcache缓存管理器
     * @return
     */
    @Bean(name = "ehCacheCacheManager")
    EhCacheCacheManager cacheManager() {
        EhCacheCacheManager cacheManager = new EhCacheCacheManager();
        //设置事物失败回滚(如果失败,缓存也会回滚)
        cacheManager.setTransactionAware(Boolean.TRUE);
        return cacheManager;
    }

}

 application.yml关键配置:

  # 关联Ehcache的配置文件
spring:
   cache:
     ehcache:
        config: classpath:ehcache.xml
     type: ehcache

三、集成Redis

主要依赖包是spring-boot-starter-cache和spring-boot-starter-data-redis,如下:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.0</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-cache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-cache</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>2021.0.0-RC1</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- mybatis plus 代码生成器 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.71</version>
        </dependency>

        <!--spring的集成缓存框架的jar-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <!--spring要集成的redis缓存jar-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

    </dependencies>

注意点:原生的spring cache不支持缓存过期,默认都是没有过期时间的,需要自定义缓存过期时间,所以cache管理器有点特殊。

redisCache管理器的实现:

@Slf4j
@Configuration
public class CustomizerRedisCacheManager {

    @Value("${redis.cache.initialCacheNamesAndDuration}")
    private String[] initialCacheNames;

    //分隔符
    private static final String SEPARATOR = "#";
    //有效时间的正则表达式
    private Pattern pattern = Pattern.compile("(?:([-+]?[0-9]+)H)|(?:([-+]?[0-9]+)M)|(?:([-+]?[0-9]+)S)", Pattern.CASE_INSENSITIVE);

    @Bean(name = "redisCacheManager")
    @Primary //自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);

        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Map<String, RedisCacheConfiguration> initialCacheConfigurations = new LinkedHashMap();

        for (String initialCacheName : initialCacheNames) {
            String cacheName = initialCacheName.substring(0, initialCacheName.indexOf(SEPARATOR));
            String durationStr = initialCacheName.substring(initialCacheName.lastIndexOf(SEPARATOR) + 1);

            Duration duration;
            try {
                duration = parseDuration(durationStr);
            } catch (Exception e) {
                log.error(e.getMessage());
                continue;
            }

            // redis配置缓存key的有效时间、key的序列化器、value的序列化器
            RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(duration) //设置缓存key有效时间
                    .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(getJackson2JsonRedisSerializer()))
                    .disableCachingNullValues();

            initialCacheConfigurations.put(cacheName, cacheConfiguration);
        }

        RedisCacheManager cacheManager = RedisCacheManager.builder(redisCacheWriter)
                .withInitialCacheConfigurations(initialCacheConfigurations)
                .build();
        return cacheManager;
    }

    /**
     * 解析时间单位字符串
     * @param duration
     * @return
     */
    private Duration parseDuration(@Nullable String duration) {
        Matcher matcher = pattern.matcher(duration);
        if(! matcher.matches()){
            throw new RuntimeException("过期时间格式是冒号后面数字跟H/M/S.");
        }

        if(duration.endsWith("H")){
            return Duration.ofHours(Long.valueOf(duration.replace("H", "")));
        }
        if(duration.endsWith("M")){
            return Duration.ofHours(Long.valueOf(duration.replace("M", "")));
        }
        if(duration.endsWith("S")){
            return Duration.ofHours(Long.valueOf(duration.replace("S", "")));
        }else{
            throw new RuntimeException("未识别的有效时间单位:" + duration);
        }
    }


    public RedisSerializer getJackson2JsonRedisSerializer(){
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper objectMapper = new ObjectMapper();
        //反序列化时智能识别变量名(识别没有按驼峰格式命名的变量名)
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        //反序列化识别对象类型
        //objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 该方法已废弃,使用activateDefaultTyping(...)代替
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance ,
                ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

        //反序列化如果未识别的属性,不抛出异常
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //反序列化如果碰到不识别的枚举值,是否作为空值解释,true:不会抛不识别的异常, 会赋空值,false:会抛不识别的异常
        objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return jackson2JsonRedisSerializer;

    }
}

application.yml的关键配置:

#redis缓存key的有效时间配置
redis:
  cache:
    initialCacheNamesAndDuration: blog:queryById#10S

#redis配置
spring:
  redis:
    host: localhost
    port: 6379
    database: 0

参考文章:

1、https://segmentfault.com/a/1190000022548904

2、springboot使用cache集成redis(自定义每个key过期时间)_JGMa_TiMo的博客-CSDN博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值