天天看点

Spring Cache缓存框架使用

作者:顽石九变

说明

Spring Cache是Spring框架的缓存抽象,集成了各种主流缓存实现(ConcurrentMap、redis、ehcache、Caffeine等)

Spring默认使用ConcurrentMap作为缓存;如果工程中引入了redis配置,则会使用redis作为缓存

Spring通过CacheManager判断具体使用哪个缓存,每个缓存都有一个具体的CacheManager(比如:EhCacheCacheManager,RedisCacheManager,CaffeineCacheManager),如果没有配置任何的CacheManager,则会使用ConcurrentMap作为缓存

常用注解说明

Spring Cache缓存框架使用

SpEL表达式说明

注解中key的写法是SpEL表达式,

Spring Cache提供了一些供我们使用的SpEL上下文数据,下表直接摘自Spring官方文档:

Spring Cache缓存框架使用

说明:

1、当我们要使用root对象的属性作为key时我们也可以将“#root”省略,因为Spring默认使用的就是root对象的属性。如:

@Cacheable(key = "targetClass + methodName +#p0")
           

2、使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。如:

@Cacheable(value="users", key="#id")
@Cacheable(value="users", key="#p0")
           

SpEL提供了多种运算符

Spring Cache缓存框架使用

在工程中使用

1、引入依赖

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

2、在工程中配置

在启动类中增加注解 @EnableCaching 开启缓存功能

在application.properties中添加可选自定义配置

Spring Cache缓存框架使用

详细配置项可参考(org.springframework.boot.autoconfigure.cache.CacheProperties)

3、在代码中使用

1)保存时,缓存返回值

@CachePut(value="dict",key="targetClass +'AppDictType'+ #entity.dictTypeCd")
@Transactional(readOnly = false)
public AppDictType save(AppDictType entity) {
    return dictTypeDao.save(entity);
}
           

2)查询时,先读取缓存,如果缓存不存在,则执行方法查询,然后更新缓存

@Cacheable(value="dict",key="targetClass +'AppDictType'+ #dictTypeCd")
public AppDictType findByDictTypeCd(String dictTypeCd) {
    return dictTypeDao.findByDictTypeCd(dictTypeCd);
}
           

3)删除时,清空缓存

@Transactional(readOnly = false)
@CacheEvict(value="dict",key="targetClass +'AppDictType'+ #dictTypeCd")
public void deleteByDictTypeCd(String dictTypeCd) {
    dictTypeDao.deleteByDictTypeCd(dictTypeCd);
}
           

4)测试用例

@Test
public void testCache() {
    String dictTypeCd = "test01";
    AppDictType entity = new AppDictType();
    entity.setDictTypeCd(dictTypeCd);
    entity.setDictTypeName("测试01");
    // 新增记录,并放入缓存
    entity = dictService.save(entity);
    // 查询缓存
    AppDictType dict = dictService.findByDictTypeCd(dictTypeCd);
    logger.info("dict1:{}", JsonUtil.obj2Json(dict));
    // 修改数据
    entity.setDictTypeName("测试0011");
    entity = dictService.save(entity);
    // 查询缓存,数据发生变化
    AppDictType dict2 = dictService.findByDictTypeCd(dictTypeCd);
    logger.info("dict2:{}", JsonUtil.obj2Json(dict3));
    // 删除记录,并清除缓存
    dictService.deleteByDictTypeCd(dictTypeCd);
    // 查询记录为空
    AppDictType dict3 = dictService.findByDictTypeCd(dictTypeCd);
    logger.info("dict3:{}", JsonUtil.obj2Json(dict4));
}
           

4、使用redis缓存

1)引入redis依赖

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

2)在application.properties 配置redis链接参数

spring.redis.host=192.168.1.144
spring.redis.port=6379
           

5、使用ehcache缓存

1)引入ehcache依赖

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

2)在application.properties 配置redis链接参数

#可以强制指定,也可以不指定,系统会自动侦测
#spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:ehcache.xml
           

3)增加ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
     <!--当ehcache把数据写到硬盘上时,将写到这个目录下,java.io.tmpdir:为默认临时文件路径-->  
    <diskStore path="java.io.tmpdir"/>
  <!--defaultCache:echcache的默认缓存策略  -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
   <!--指定名称的缓存配置-->
    <cache name="fileConfig"
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
        <!-- 
        缓存配置说明:
        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:内存数量最大时是否清除。
        -->
</ehcache>
           

4)在方法中指定cacheName

@Cacheable("fileConfig")
public SysFileConfig findByAppCode(String appCode) {
    SysFileConfig config = fileConfigDao.selectOne(new QueryWrapper<SysFileConfig>().eq("app_code", appCode));
    return config;
}
           

5、关闭spring cache缓存

如果已经开启了@EnableCaching缓存,在某些环境下又不想使用缓存,又不想修改原有代码。

可通过如下配置关闭缓存:

spring.cache.type=none
           

参考

  • https://www.cnblogs.com/yueshutong/p/9381540.html
  • https://docs.spring.io/spring-boot/docs/2.2.0.RELEASE/reference/htmlsingle/#boot-features-caching