Springboot工程配置ehcache缓存

Springboot添加缓存很方便,个人网站选择的ehcache缓存。

一、导入maven依赖

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

二、在启动配中添加注解

@EnableCaching/*ehcache缓存*/
@SpringBootApplication(scanBasePackages = "com.blog")
public class SpringbootMybatisBlogApplication  extends WebMvcConfigurerAdapter {

三、添加配置文件

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="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" />
    <cache name="getArticle" eternal="false" maxElementsInMemory="100" overflowToDisk="false"                      diskPersistent="false"
           timeToIdleSeconds="0" timeToLiveSeconds="86400" memoryStoreEvictionPolicy="LRU" />
    </ehcache>

各参数属性可以自行百度。

四、在serviceImpl层中添加缓存注解

@Override
@Cacheable(value = "getArticle")
public List<BlogModel> getArticle() {
    List<BlogModel> articleList = blogDao.getArticle();
      return  articleList;
}

运行代码,缓存生效。

注解:@Cacheable 先从缓存中查,没有则查询数据库、 @CacheEvict 清空缓存 、@CachePut 表示缓存方法,每次都会去查询重新放入。

猜你喜欢

转载自blog.csdn.net/jinseaa/article/details/83342479