SpringBoot 使用 EhCache2.x 缓存(三十一)

时间:2023-03-08 19:48:19
SpringBoot 使用 EhCache2.x 缓存(三十一)

SpringBoot 使用 EhCache2.x 缓存入门很简单,废话少说上干货: 1.在POM.xml中增加jar包

<!--开启 cache 缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- ehcache 缓存 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>

2.在resource文件夹下创建文件ehcache.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">
<defaultCache
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU" /> <cache
name="users"
eternal="false"
maxElementsInMemory="100"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="300"
memoryStoreEvictionPolicy="LRU" />
</ehcache>

3.在 Spring Boot 主类加上开启缓存的注解@EnableCaching

@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

4.使用示例

介绍一下 Ehcache 在 Spring 中的注解

  • @Cacheable

Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中

  • @CacheEvict

清除缓存

  • @CachePut

在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中

这三个方法中都有两个主要的属性:value 指的是 ehcache.xml 中的缓存策略空间;key 指的是缓存的标识,同时可以用 # 来引用参数。


@Service
public class UserService { //这里的单引号不能少,否则会报错,被识别是一个对象
private static final String CACHE_KEY = "'user'";
private static final String DEMO_CACHE_NAME = "users"; @Autowired
private UserDao userDao; //删除用户数据
@CacheEvict(value = DEMO_CACHE_NAME,key = "'user_'+#uuid")//这是清除缓存
public void delete(String uuid){
userDao.delete(uuid);
} //更新用户数据
@CachePut(value = DEMO_CACHE_NAME,key = "'user_'+#user.getUuid()")
public User update(User user) throws CacheException{
User user1 = userDao.findByUuid(user.getUuid());
if (null == user1){
throw new CacheException("Not Find");
}
user1.setAge(user.getAge());
user1.setName(user.getName());
return user1;
} //查找用户数据
@Cacheable(value=DEMO_CACHE_NAME,key="'user_'+#uuid")
public User findByUuid(String uuid){
//若找不到缓存将打印出提示语句
System.err.println("没有走缓存!"+uuid);
return userDao.findByUuid(uuid);
} //保存用户数据
@CacheEvict(value=DEMO_CACHE_NAME,key=CACHE_KEY)
public int save(User user){
return userDao.save(user);
}
}