每个人都应当学会独立地去思考、去寻找答案,而不是一味地伸手向他人索取所谓的标准答案。 首先,别成为“拿来主义”者,其次远离"拿来主义"的人。
1.搭建spring boot 项目
2. pom.xml文件中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<!--
磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
path:指定在硬盘上存储对象的路径
path可以配置的目录有:
user.home(用户的家目录)
user.dir(用户当前的工作目录)
java.io.tmpdir(默认的临时目录)
ehcache.disk.store.dir(ehcache的配置目录)
绝对路径(如:d:\\ehcache)
查看路径方法:String tmpDir = System.getProperty("java.io.tmpdir");
-->
<diskStore path="java.io.tmpdir" />
<!--
defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象
eternal:代表对象是否永不过期 (指定true则下面两项配置需为0无限期)
timeToIdleSeconds:最大的发呆时间 /秒
timeToLiveSeconds:最大的存活时间 /秒
overflowToDisk:是否允许对象被写入到磁盘
说明:下列配置自缓存建立起600秒(10分钟)有效 。
在有效的600秒(10分钟)内,如果连续120秒(2分钟)未访问缓存,则缓存失效。
就算有访问,也只会存活600秒。
-->
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="600" timeToLiveSeconds="600" overflowToDisk="true" />
<!--有效时间: 7200秒 = 2小时 ,连续180秒 = 3分钟未访问缓存,则失效-->
<cache name="userCache" maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="1800" timeToLiveSeconds="7200" overflowToDisk="true" />
</ehcache>
@EnableCaching
注解。@Service
public class UserServiceImpl implements IUserService {
@Resource
private UserRepository userRepository;
@Override
@Cacheable(value = "userCache", key = "#user.id")
public boolean addUser(UserEntity user) {
return userRepository.saveAndFlush(user).getId() != null;
}
@Override
@CachePut(value = "userCache", key = "#user.id")
public boolean updateUser(UserEntity user) {
return userRepository.saveAndFlush(user).getId() != null;
}
@Override
@CacheEvict(value = "userCache", key = "#id")
public boolean deleteUser(Long id) {
return false;
}
@Override
@Cacheable(value = "userCache", key = "#id")
public UserEntity selectUser(Long id) {
return null;
}
}
当你想要删除某一缓存区所有缓存时,可以使用 @CacheEvict(value = "userCache", allEntries = true), 删除userCache中所有的缓存。
每个人都“画地为牢”,把志同道合者划入圈内,把异己者排除在外。选好你的“地”,划好你的“圈”。“亲贤臣,远小人,此先汉所以兴隆也;亲小人,远贤臣,此后汉所以倾颓也。” 把自己经营好,就相当于把自己的圈子经营好,和志同道合者,一同去征服星辰大海!
示例代码可在我的 github.com 中找到。
欢迎关注我。
公众号: 锅外的大佬 ,欢迎加群~
博客地址: http://www.developlee.top
原文:https://www.cnblogs.com/liululee/p/13354481.html