第一节:Spring 缓存技术概述
Spring 缓存技术是 Spring Framework 提供的一套抽象化的缓存机制,允许开发者通过简单的注解和配置,将缓存逻辑透明地应用到方法调用中。其核心目标是 减少重复计算 和 降低数据库访问压力,提升应用性能,同时保持代码的简洁性。
1)核心特点
1.声明式缓存:通过注解(如 @Cacheable)声明方法需要缓存,无需侵入业务逻辑。
2.抽象层设计:支持多种缓存实现(如 Ehcache、Redis、Caffeine 等),通过统一接口切换。
3.灵活配置:可自定义缓存策略(过期时间、淘汰策略等)和缓存管理器。
2)Spring缓存机制的工作原理
Spring的缓存机制采用了典型的两层架构,即内核层和扩展层。内核层相当于对缓存本身的一种抽象,抽取了与缓存相关的最核心的操作方法;而扩展层则是基于内核层的抽象,分别集成业界主流的缓存工具,从而对缓存的核心操作方法提供实现方案。
在Spring缓存中,Cache和CacheManager接口定义了内核层组件,而把两个接口的各种实现类看作扩展组件。Cache接口定义了缓存的基本操作,如获取缓存值、向缓存中放数据、从缓存中移除数据等。而CacheManager接口则用于管理多个Cache实例,提供统一的缓存管理接口。
Spring通过AOP技术,可以在不改变代码逻辑的情况下,为方法调用添加缓存逻辑。开发者只需通过注解(如@Cacheable、@CachePut、@CacheEvict等)声明方法的缓存行为,Spring即可在方法调用前后自动执行缓存操作。
一、缓存搭建过程:
1、首先导入缓存依赖:
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.9.2</version>
</dependency>
2、创建ehcache.xml配置文件:
<?xml version="1.0" encoding="GBK" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.ehcache.org/ehcache.xsd http://www.ehcache.org/ehcache.xsd"
updateCheck="true">
<diskStore path="java.io.tmpdir"/>
<!-- 默认的缓存区 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"/>
<!-- 自定义名为person的缓存区 -->
<cache name="person"
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="300"
timeToLiveSeconds="600"/>
</ehcache>
3、整合spring-mvc.xml配置文件,我们在原有的配置文件基础上进行修改,将ehcache.xml引入:
<!-- spring缓存配置 start:启用缓存注解 -->
<cache:annotation-driven />
<!-- 指定在service层使用缓存 -->
<context:component-scan base-package="service"></context:component-scan>
<!-- 配置EhCacheCacheManager -->
<bean id="ehCacheManagerFactory" class="org.springframework.cac