spring cache (ehcache方式)


前置

会演示springcache的使用方式
项目地址

前置配置

本篇文章是基于上篇文章进行: spring cache (默认方式)

强调:

在追踪源码的时候发现, 是通过注入ehCacheCacheManager进行文件的初始化, 当然解析xml文件也是该地方开始. 也就有了MyEhCacheCacheConfiguration,java方法. 大致思路同源码一致, 只是对获取的数据进行拦截, 增加部分数据, 进行一遍赋值操作

源码部分
spring cache (默认方式) 一致, 只是实现缓存的方式不一样

关键类: org.springframework.cache.Cache
org.springframework.cache.interceptor.CacheInterceptor#invoke
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
实现类: org.springframework.cache.ehcache.EhCacheCache

相关缓存文章

spring cache (默认方式)
spring cache (Redis方式)
spring cache (ehcache方式)


pom: jar

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>ehcache</artifactId>
</dependency>

<dependency>
	<groupId>javax.cache</groupId>
	<artifactId>cache-api</artifactId>
</dependency>

<!-- 反射工具包 -->
<dependency>
	<groupId>org.reflections</groupId>
	<artifactId>reflections</artifactId>
	<version>0.9.10</version>
</dependency>

配置文件:

ehcache.xml

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

    <!-- 磁盘缓存位置
    path属性可以配置的目录有:
    user.home(用户的家目录)
    user.dir(用户当前的工作目录)
    java.io.tmpdir(默认的临时目录)
    ehcache.disk.store.dir(ehcache的配置目录)
    绝对路径(如:d:\\ehcache)
    -->
    <diskStore path="F:\upload\EhCache"/>

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


    <!-- 默认缓存 -->
    <defaultCache
            eternal="true"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            diskPersistent="true"
            timeToIdleSeconds="0"
            timeToLiveSeconds="0"
            memoryStoreEvictionPolicy="LRU"/>

    <!-- 自定义缓存 name需与 @Cacheable(value = "selectById")的value值一直 -->
    <!-- 如果想自定义就需要在此地方依次罗列, 参考: MyEhCacheCacheConfiguration.java -->
    <cache
            name="CUSTOMIZE_GLOBAL"
            eternal="true"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            diskPersistent="true"
            timeToIdleSeconds="0"
            timeToLiveSeconds="0"
            memoryStoreEvictionPolicy="LRU"/>


</ehcache>

application.yml

spring:
  cache:
    # 程序启动时创建的缓存名称
    cache-names: chaim-name
    # 缓存类型 org.springframework.boot.autoconfigure.cache.CacheType
    type: ehcache
    ehcache:
      config: classpath:ehcache.xml


MyEhCacheCacheConfiguration.java

package com.chaim.spring.cache.ehcache.config;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.Configuration;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.ehcache.EhCacheManagerUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author Chaim
 * @date 2022/9/23 0:11
 */
@Component
@Primary
public class MyEhCacheCacheConfiguration {
    /**
     * 固定 ehcache.xml 中 cache标签name值为: CACHE_NAME 就进行全局配置
     */
    private static final String CACHE_NAME = "CUSTOMIZE_GLOBAL";
    /**
     * 要扫描注解的包路径
     */
    private static final String PACKAGE_NAME = "com.chaim.spring.cache.ehcache.controller";

    /**
     * 重写 org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration#ehCacheCacheManager
     * 实现: 多 cache 标签自动添加
     *
     * @param cacheProperties
     * @return
     */
    @Bean
    CacheManager ehCacheCacheManager(CacheProperties cacheProperties) {
        Resource location = cacheProperties.resolveConfigLocation(cacheProperties.getEhcache().getConfig());
        if (location != null) {
            // 源码: 从给定资源中解析 EhCache 配置,以供进一步使用
            Configuration configuration = EhCacheManagerUtils.parseConfiguration(location);
            // 对获取的 ehcache 资源进行重写
            Map<String, CacheConfiguration> cacheConfigurations = configuration.getCacheConfigurations();
            // 校验其是否是全局标签 (配置该标签, 就标记需要缓存的都是此一个文件进行加载)
            CacheConfiguration cacheConfiguration = cacheConfigurations.get(CACHE_NAME);
            if (cacheConfiguration != null) {
                // 获取指定路径下的 @Cacheable 的 value 值, 也就是需要进行创建的缓存文件名
                Set<String> allCacheableValue = this.getAllCacheableValue();
                allCacheableValue.forEach(key -> {
                    if (cacheConfigurations.get(key) == null) {
                        // 对象克隆, 该处涉及深浅拷贝
                        CacheConfiguration clone = cacheConfiguration.clone();
                        // 修改缓存文件名为 @Cacheable 的 value 值
                        clone.name(key);
                        // 将需要的值 PUT 进入 CacheConfiguration, 对应的cache标签值除name其余不变
                        cacheConfigurations.put(key, clone);
                    }
                });
                // 移除全局配置配置文件, 避免创建该文件无效
                cacheConfigurations.remove(CACHE_NAME);
            }
            // 源码: 返回CacheManager
            return new CacheManager(configuration);
        }
        return EhCacheManagerUtils.buildCacheManager();
    }

    /**
     * 获取指定路径下所有 Cacheable 的 value 值
     *
     * @return Cacheable -> value
     */
    private Set<String> getAllCacheableValue() {
        Set<String> set = new HashSet<>();

        // 要扫描的包
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
                .addUrls(ClasspathHelper.forPackage(PACKAGE_NAME))
                .addScanners(new MethodAnnotationsScanner());
        Reflections ref = new Reflections(configurationBuilder);

        // 获取扫描到的标记注解的集合
        Set<Method> methodsAnnotatedWith = ref.getMethodsAnnotatedWith(Cacheable.class);
        for (Method method : methodsAnnotatedWith) {
            Cacheable cacheable = method.getAnnotation(Cacheable.class);
            String[] value = cacheable.value();
            set.addAll(Arrays.asList(value));
        }
        return set;
    }
}

效果图

禁用 MyEhCacheCacheConfiguration.java

在这里插入图片描述


启用 MyEhCacheCacheConfiguration.java

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值