springBoot开启缓存

1、pom文件引入

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

2、新建ehcache.xml 文件 放在classpath目录 maven的resources目录

<?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">
	<!--
            磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于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/Tmp_EhCache" />
	<!-- 默认配置 -->
	<!--
            defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
            maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象
            eternal:代表对象是否永不过期 (指定true则下面两项配置需为0无限期)
            timeToIdleSeconds:最大的发呆时间 /秒
            timeToLiveSeconds:最大的存活时间 /秒
            overflowToDisk:是否允许对象被写入到磁盘
            说明:下列配置自缓存建立起600秒(10分钟)有效 。
            在有效的600秒(10分钟)内,如果连续120秒(2分钟)未访问缓存,则缓存失效。
            就算有访问,也只会存活600秒。
         -->
	<defaultCache maxElementsInMemory="5000" eternal="false"
		timeToIdleSeconds="120" timeToLiveSeconds="120"
		memoryStoreEvictionPolicy="LRU" overflowToDisk="false" />
	<cache name="baseCache" maxElementsInMemory="10000"
		maxElementsOnDisk="100000" />
</ehcache>

3、代码使用Cacheable

@CacheConfig(cacheNames = "baseCache")  //这里的名字跟配置文件的一致
public interface UserMapper {
	@Select("select * from users where name=#{name}")
	@Cacheable
	UserEntity findName(@Param("name") String name);
}

4、清除缓存

在某个Controller中加入以下代码,可通过调用接口清除缓存
@Autowired
private CacheManager cacheManager;
@RequestMapping("/remoKey")
public void remoKey() {
	cacheManager.getCache("baseCache").clear();
}

5、启动类开启缓存

@EnableCaching // 开启缓存注解

6、效果解释

 @RequestMapping("/testCache")
    @Cacheable
    public String testCache() {
        System.out.println("hh");
        return "hh";
    }
    
 我在controller中写了一个方法加上缓存注解,注意类上也要加上相应的注解,执行第二遍的时候,testCache()方法直接不执行了,都不打印"hh"了,直接返回缓存中的数据。

7、再学一招:如果应用集群部署环境,我们一般都是使用redis作为缓存服务器

先从redis中查找数据,如果不存在则从数据库中查询,这里就会引入缓存击穿、缓存雪崩等问题,在后续专题会推出相关解决访问,敬请期待。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值