Spring Cache

1,909 阅读4分钟

Spring 定义了CacheManager和Cache接口来提供缓存的抽象,可以通过切换的CacheManager的实现类,来使用不同的缓存技术。CacheManager的实现有:ConcurrentMapCacheManager、EhCacheCacheManager、RedisCacheManager等。

使用

只有public方法才可以被缓存

application配置

spring.cache.type=#缓存的技术类型
spring.cache.cache-names=应用程序启动创建缓存的名称
spring.cache.*.config=cache的配置文件位置

配置类配置

加入注解 @EnableCaching 开启缓存

缓存注解

  • @Cacheable
// 在调用方法之前,先查缓存,有值则返回,无值调用方法查询并放到缓存
@Cacheable(cacheNames = "user",key = "#user.userId")
public User getById(User user){
}
  • @CachePut
// 调用方法查询并将结果放到缓存
@CachePut(cacheNames = "user", key = "#user.userId")
public User getById(User user){
}
  • @CacheEvict
// 在缓存中清除一个或多个条目。

@CacheEvict(cacheNames = "user",key = "#user.userId")
public boolean remove(User user){
    return true;
}
  • @Caching
// 分组的注解,能够同时应用多个其他的缓存注解。
@Caching(cacheable = {@Cacheable(cacheNames = "user", key = "#user.userId"),
        @Cacheable(cacheNames = "user", key = "#user.userName")})
public User getUser(User user){
    User user1 = new User();
    user1.setUserId("123");
    log.info("查询用户:"+user1.toString());
    return user1;
}

使用ConcurrentHashMap做缓存

配置

spring.cache.type=simple

使用Ehcache2.X

ehcache提供了用内存,磁盘文件存储,以及分布式存储。提供 LRU、LFU 和 FIFO 缓存策略

  • 配置
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:ehcache2.xml
  • ehcache2.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">

    <!-- 磁盘缓存位置 -->
    <diskStore path="e:\ehcache2"/>

    <!-- 默认缓存 -->
    <defaultCache
        eternal="false"
        maxEntriesLocalHeap="1000"
        timeToIdleSeconds="3600"
        timeToLiveSeconds="1800"
        overflowToDisk="true"
        memoryStoreEvictionPolicy = "LRU">
    </defaultCache>

    <!-- 此缓存最多可以存活timeToLiveSeconds秒,如果期间超过timeToIdleSeconds秒未访问,缓存失效 -->
    <cache
            name = "userCache"
            eternal = "false"
            maxElementsInMemory = "100"
            overflowToDisk = "false"
            diskPersistent = "false"
            timeToIdleSeconds = "120"
            timeToLiveSeconds = "180"
            memoryStoreEvictionPolicy = "LRU"/>

    <!-- maxElementsInMemory 内存中最大缓存对象数,看着自己的heap大小来搞 -->
    <!-- eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false -->
    <!-- maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大 -->
    <!-- overflowToDisk:true表示当内存缓存的对象数目达到了maxElementsInMemory界限后,
    会把溢出的对象写到硬盘缓存中。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实现了Serializable接口才行。-->
    <!-- diskSpoolBufferSizeMB:磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区。-->
    <!-- diskPersistent:是否缓存虚拟机重启期数据  -->
    <!-- diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认为120秒 -->

    <!-- timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,
    如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,
    EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,
    则表示对象可以无限期地处于空闲状态 -->

    <!-- timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,
    如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期,
    EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。如果该属性值为0,
    则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义 -->

    <!-- memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,
    Ehcache将会根据指定的策略去清理内存。可选策略有:LRU(最近最少使用,默认策略)、
    FIFO(先进先出)、LFU(最少访问次数)。-->

    <cache name="user"
       maxEntriesLocalHeap="2000"
       eternal="false"
       timeToIdleSeconds="600"
       timeToLiveSeconds="0"
       overflowToDisk="false"
       statistics="true">
    </cache>

</ehcache>
	

使用Ehcache3.X

配置

# ehcache3
spring.cache.type=jcache
spring.cache.jcache.config=classpath:ehcache3.xml

ehcache3.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        xmlns='http://www.ehcache.org/v3'
        xsi:schemaLocation="http://www.ehcache.org/v3
        http://www.ehcache.org/schema/ehcache-core.xsd">
    <!-- 缓存到磁盘使用的目录 -->
    <persistence directory="e:\ehcache3"/>
    <!-- 定义一个缓存仓库,alias也就是 @Cacheable 的 cacheNames 属性 -->
    <cache alias="user" uses-template="default">
        <!--指定key的类型,@Cacheable 指定的key类型-->
        <key-type>java.lang.String</key-type>
        <!--指定返回类型,也就是方法返回的数据类型-->
        <value-type>com.pengtech.xup.User</value-type>
    </cache>

    <cache-template name="default">
        <!--
           指定缓存的过期策略,tti,ttil,none。以及他们的单位时,分,秒,日
           这里的配置表示,在缓存超过1H后没使用过,即删除
       -->
        <expiry>
            <ttl unit="minutes">30</ttl>
        </expiry>
        <!--
           指定缓存的缓存位置,可以指定堆内存,堆外内存,磁盘,以及他们最大使用的空间
       -->
        <resources>
            <heap unit="entries">2000</heap>
            <offheap unit="MB">100</offheap>
            <disk unit="GB" persistent="true">1</disk>
        </resources>
    </cache-template>


</config>