springboot2 - ehcache

介绍 ehcache 一下在 spring 环境下的应用。

如果是单机系统,ehcache 一般是首选方案,想通过切换 redis 提高性能,意义不大,反而会增加部署和维护负担。

工具函数

如果想在 spring 环境下,封装自己的工具函数,下面这些基础代码估计会用到。

场景:像是 Excel 导入数据,需要大批量更新缓存时,手动操作缓存反而更容易。

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

@Service
class CacheUtils{

    // 获取 spring 容器中的缓存管理
    @Resource
    private CacheManager cacheManager;

    public void demo() {
        // 根据 name 找到对应的 cache
        Cache cache = cacheManager.getCache("cache-name");
        // 获取 Cache 对象实体
        net.sf.ehcache.Cache nativeCache = (net.sf.ehcache.Cache) cache.getNativeCache();
    }
}

@CacheConfig

/**
 * @CacheConfig 在类上使用,声明这个类使用的缓存名称。
 *
 * 很多人可能没用过这个注解,不用也是可以的,因为 @Cacheable 也有一个 cacheNames,效果一致。
 */
@Service
@CacheConfig(cacheNames = "user")
public class UserService {
}

@Cacheable

class Test {

    /**
     * Cacheable 注解用在方法上;数据查询时,对函数的返回值进行缓存。
     *
     * key 值就是缓存中用的名字,可以专门定制一套生成策略;
     * 下面这种,用的是 spring 的 EL 表达式,将参数中的 id 拼接上 'test' 作为 key 值。
     *
     * cacheNames 声明你用的是什么缓存,ehcache 中对应的是 cache 的 name。
     *
     * @param id 能唯一定位到数据的值
     */
    @Cacheable(cacheNames = "user", key = "'test' + #id")
    public User getUserById(Long id) {
        return dao.getUserById(id);
    }
}

注解中其余字段说明:

  • cacheNames/value:缓存名称;
  • key:缓存数据使用的 key;
  • keyGenerator:用于指定 key 的生成策略,可以封装一个工具,自动生成 key;
  • cacheManager:指定缓存管理器;
  • condition:符合条件才缓存,例:@Cacheable(condition = "#id > 1");
  • unless:除非,对返回值进行判断,满足条件的不缓存;
  • sync:是否使用异步模式。

@CachePut

class Test{

    /**
     * CachePut 注解用在方法上:数据变化的时候,将缓存中的数据,更新成函数的返回值。
     */
    @CachePut(key = "#id")
    public User updateUserById(User user) { 
        return dao.updateUserById(user); 
    }
}

@CacheEvict

class Test{

    /**
     * CacheEvict 注解用在方法上:数据发生删除的时候,清除缓存。
     */
    @CacheEvict(key = "#id")
    public void deleteUserById(Long id) {
        dao.deleteUserById(id);
    }
}

Maven 依赖


<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>2.10.6</version>
    </dependency>
</dependencies>

yml 配置

# ehcache缓存配置,注意调整 yml 配置的时候,还需要调整 maven 依赖
spring:
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache.xml

ehcache.xml

如果你的 yml 也指定为 classpath:ehcache.xml,那就放在 resources 根目录,位置可按需调整。

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

    <!-- java.io.tmpdir:默认的临时文件存放路径;-->
    <!-- user.home:用户文件夹;-->
    <!-- user.dir:工程目录。-->
    <diskStore path="java.io.tmpdir"/> 

    <!-- 默认缓存,在程序中创建缓存时的模版 -->
    <defaultCache maxElementsInMemory="10000"
                  eternal="false"
                  timeToIdleSeconds="120"
                  timeToLiveSeconds="120"
                  overflowToDisk="true"
                  maxElementsOnDisk="100000"
                  diskPersistent="false"
                  diskExpiryThreadIntervalSeconds="120"
                  memoryStoreEvictionPolicy="LRU"/>

    <!-- 
                    配置自定义缓存
    maxElementsInMemory:缓存中允许创建的最大对象数
    eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
    timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,
                                两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,
                                如果该值是 0 就意味着元素可以停顿无穷长的时间。
    timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,
                    这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
    overflowToDisk:内存不足时,是否启用磁盘缓存。
    memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。默认策略是LRU(最近最少使用)。
            你可以设置为FIFO(先进先出)或是LFU(较少使用)
    -->

    <cache name="security"
           maxElementsInMemory="10000"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LRU"/>
</ehcache>

posted on 2024-05-21 09:16  疯狂的妞妞  阅读(37)  评论(0编辑  收藏  举报

导航