Spring 缓存抽象层概述

Spring 缓存抽象层为 Java 应用程序提供了一种统一的方式来管理缓存,它使得开发者可以在不依赖具体缓存实现的情况下使用缓存功能。其核心目标是简化缓存的使用,降低代码与具体缓存技术的耦合度。

主要特性

  1. 注解驱动:Spring 提供了一系列注解,如 @Cacheable@CachePut@CacheEvict@Caching,可以方便地将缓存功能集成到方法上。
  2. 缓存管理器抽象:Spring 定义了 CacheManager 接口,它是缓存抽象层的核心,负责管理多个 Cache 实例。不同的缓存实现(如 Ehcache、Redis 等)都有对应的 CacheManager 实现。
  3. 事务支持:Spring 的缓存抽象层与 Spring 的事务管理集成,确保在事务提交或回滚时,缓存操作能够正确处理。

常用注解说明

  • @Cacheable:标记在方法上,表示该方法的结果可以被缓存。如果缓存中已经存在该方法的结果,则直接从缓存中获取,不再执行方法体。
  • @CachePut:标记在方法上,无论缓存中是否存在该方法的结果,都会执行方法体,并将结果更新到缓存中。
  • @CacheEvict:标记在方法上,用于从缓存中移除指定的缓存项。
  • @Caching:用于组合多个缓存注解。

自定义缓存策略

步骤 1:配置缓存管理器

首先,你需要配置一个缓存管理器。以下是一个使用 Ehcache 作为缓存实现的示例:

import net.sf.ehcache.config.CacheConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheManagerFactoryBean().getObject());
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
        EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();
        factory.setConfigLocation(new ClassPathResource("ehcache.xml"));
        factory.setShared(true);
        return factory;
    }
}

步骤 2:创建自定义缓存配置文件

src/main/resources 目录下创建 ehcache.xml 文件,定义自定义的缓存策略:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">

    <diskStore path="java.io.tmpdir"/>

    <defaultCache
            maxEntriesLocalHeap="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxEntriesLocalDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>

    <cache name="myCustomCache"
           maxEntriesLocalHeap="500"
           eternal="false"
           timeToIdleSeconds="180"
           timeToLiveSeconds="180"
           memoryStoreEvictionPolicy="LFU">
    </cache>
</ehcache>

在这个配置文件中,我们定义了一个默认缓存和一个名为 myCustomCache 的自定义缓存。myCustomCache 缓存的最大堆内存条目数为 500,空闲时间和存活时间均为 180 秒,内存淘汰策略为 LFU(最不经常使用)。

步骤 3:使用自定义缓存

在你的服务类中,使用 @Cacheable 注解指定使用自定义缓存:

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Cacheable("myCustomCache")
    public String getData(String key) {
        // 模拟从数据库或其他数据源获取数据
        System.out.println("Fetching data from source...");
        return "Data for key: " + key;
    }
}

在这个示例中,getData 方法的结果会被缓存到 myCustomCache 中。如果下次调用该方法时传入相同的 key,则会直接从缓存中获取结果,而不会再次执行方法体。

通过以上步骤,你可以使用 Spring 的缓存抽象层,并自定义缓存策略。