一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
二、添加缓存配置文件(将ehcache.xml文件复制到项目的resources目录下)
ehcache文件位置:code-samples/src/main/resources/xml/
也可用下面代码
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true" monitoring="autodetect"
dynamicConfig="true">
<diskStore path="java.io.tmpdir"/>
<transactionManagerLookup class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup"
properties="jndiName=java:/TransactionManager" propertySeparator=";"/>
<cacheManagerEventListenerFactory class="" properties=""/>
<cacheManagerPeerProviderFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
properties="peerDiscovery=automatic,
multicastGroupAddress=230.0.0.1,
multicastGroupPort=4446, timeToLive=1"
propertySeparator=","
/>
<cacheManagerPeerListenerFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/>
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskSpoolBufferSizeMB="30"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<cache name="user_cache"
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="1000"
eternal="false"
diskSpoolBufferSizeMB="20"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU"
transactionalMode="off">
<persistence strategy="localTempSwap"/>
</cache>
<cache name="sampleCache2"
maxEntriesLocalHeap="1000"
eternal="true"
memoryStoreEvictionPolicy="FIFO"
/>
<cache name="sampleCache3"
maxEntriesLocalHeap="500"
eternal="false"
overflowToDisk="true"
diskPersistent="true"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
diskExpiryThreadIntervalSeconds="1"
memoryStoreEvictionPolicy="LFU">
</cache>
<cache name="sampleReplicatedCache1"
maxEntriesLocalHeap="10"
eternal="false"
timeToIdleSeconds="100"
timeToLiveSeconds="100">
<cacheEventListenerFactory
class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/>
<bootstrapCacheLoaderFactory
class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"/>
</cache>
<cache name="sampleRepicatedCache2"
maxEntriesLocalHeap="10"
eternal="false"
timeToIdleSeconds="100"
timeToLiveSeconds="100">
<cacheEventListenerFactory
class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
properties="replicateAsynchronously=false, replicatePuts=false,
replicatePutsViaCopy=false, replicateUpdates=true,
replicateUpdatesViaCopy=true, replicateRemovals=false"/>
</cache>
<cache name="sampleReplicatedCache3"
maxEntriesLocalHeap="10"
eternal="false"
timeToIdleSeconds="100"
timeToLiveSeconds="100">
<cacheEventListenerFactory
class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
properties="asynchronousReplicationIntervalMillis=200"/>
<persistence strategy="localTempSwap"/>
</cache>
</ehcache>
三、编写模拟Dao层类
其中@CacheConfig中的name要与配置文件中cache的那么一样
@Repository
@CacheConfig(cacheNames = "user_cache")//缓存名
public class UserDao {
@Cacheable//下面方法进行缓存,缓存的key为参数id,缓存内容为返回的结果user
public User getUserById(Integer id) {
System.out.println("getUserById");
User user = new User();
user.setId(id);
user.setUsername("刘林栋");
user.setPhone("135+145454");
user.setAge(18);
return user;
}
@CachePut(key = "#user1.id")//更新缓存,更新所需的key为参数user1.id,内容为返回的结果
public User putUser(User user1) {
System.out.println("put");
user1.setUsername("zst");
return user1;
}
@CacheEvict(key = "#id1")//删除缓存,根据key删除(key为参数id1)
public void deleteUser(Integer id1) {
System.out.println("delete");
}
}
四、编写测试类
@SpringBootTest
class AlltestApplicationTests {
@Autowired
UserDao userDao;
@Test
public void test() {
//第一次执行getUserById方法,将结果写进内存
userDao.getUserById(1);
//再次运行此方法不执行,直接从内存中拿结果
userDao.getUserById(1);
//第一次执行deleteUser方法,删除key为1的缓存
userDao.deleteUser(1);
//因为已经删除了key为1的缓存,所以执行此方法时进入方法运行
User user = userDao.getUserById(1);
//输出user的信息
System.out.println(user);
User u = new User();
u.setId(1);
//将u(id=1)传给putUser方法,方法体为setUsername=zst
userDao.putUser(u);
//已经存在key为1的缓存,直接读缓存,不进入方法
User u2 = userDao.getUserById(1);
System.out.println(u2);
}
}