springboot杂谈(四)springboot+ehcache实现缓存

本文介绍如何在Spring Boot项目中配置和使用Ehcache缓存,包括添加依赖、配置缓存策略、启用缓存及使用注解进行缓存操作。通过具体示例,展示了如何设置缓存的最大元素数量、缓存策略等参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、添加依赖
首先编辑项目的 pom.xml 文件,添加 spring-boot-starter-cache 依赖以及 Ehcache 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
 	<groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

二、添加缓存配置文件
resources:config/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">
    <diskStore path="java.io.tmpdir/Tmp_EhCache"/>
    <defaultCache eternal="false" maxElementsInMemory="1000"
                  overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="60"
                  timeToLiveSeconds="60" memoryStoreEvictionPolicy="LRU"/>
    <cache name="user" eternal="false" maxElementsInMemory="10000"
           overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="120"
           timeToLiveSeconds="120" memoryStoreEvictionPolicy="LFU"/>
</ehcache>
name:缓存名称;
eternal:缓存对象是否永久有效,若是永久有效,则timeout配置不起作用;值:true/false;
maxElementsInMemory:缓存最大个数;
overflowToDisk:表示缓存个数达到maxElementsInMemory时,是否将缓存对象写入到磁盘中;
diskPersistent:是否缓存虚拟机缓存期数据;
timeToIdleSeconds:缓存对象在失效前的允许闲置时间(单位:秒),默认是0,也就是缓存时间不限;只有当eternal=false时生效;
timeToLiveSeconds:缓存对象在失效前的允许存货时间(单位:秒),默认是0,也就是缓存时间不限;只有当eternal=false时生效;
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:缓存策略;LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数);
			FIFO,first in first out,这个是大家最熟的,先进先出。
            LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
            LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。

三、引入缓存配置文件
在application.yml中引入ehcache缓存配置文件;

spring:
  cache:
    type: ehcache
    ehcache:
      config: classpath:config/ehcache.xml

四、开启缓存
在springboot启动类上加上@EnableCaching注解用来开启缓存,不加注解则不会开启缓存;

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

五、编写测试代码,加上注解插入和读取缓存;

@Service
public class FileServiceImpl implements FileService {
	@Autowired
	private FileDao sysFileMapper;

	@Autowired
	private BootdoConfig bootdoConfig;
	@Override
	public FileDO get(Long id){
		return sysFileMapper.get(id);
	}
	
	@Override
	@Cacheable(value="user" ,key="'filelist'")
	public List<FileDO> list(Map<String, Object> map){
		System.out.println("list:没有走缓存!");
		return sysFileMapper.list(map);
	}
@Cacheable:spring在每次执行前都会在cache中检查一下是否存在相同key的缓存数据,若存在则不再执行该方法,直接在缓存中取出该数据返回,否则才会执行并将数据添加到缓存当中;key是缓存存入的key,value是使用的缓存名称(ehcache.xml),比如:@Cacheable(value="user" ,key="'filelist'");
@CachePut:可以写在类和方法上,使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。比如	@CachePut(value="user" ,key="'filelist'")
@CacheEvict:清除缓存;比如:@CacheEvict(value = CACHE_NAME_B, key = CACHE_KEY)

调用测试类中的测试方法,可以发现缓存已经生效了,第一次访问打印了‘list:没有走缓存’,第二次访问没有打印,直接读取的缓存;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值