Spring Boot学习笔记(七)缓存之ehche

第一步 pom.xml添加依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.6</version>
        </dependency>

第二步 添加ehche.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <diskStore path="java.io.tmpdir"/>

    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <cache name="testCache"
                  maxElementsInMemory="10000"
                  eternal="false"
                  timeToIdleSeconds="120"
                  timeToLiveSeconds="120"
                  maxElementsOnDisk="10000000"
                  diskExpiryThreadIntervalSeconds="120"
                  memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

第三步 在application.yml中把ehche配上

cache:
    type: ehcache
    ehcache:
        config: ehcache.xml

第四步 在启动类Application中添加@EnableCaching启用缓存

package org.test;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@ServletComponentScan //扫描servlet注解
@EnableCaching
public class Application {

    public static void main(String[] args) {
        org.springframework.boot.SpringApplication.run(Application.class, args);
    }

}

第五步 在DAO层添加缓存注解,并设置要使用的缓存配置名称

package org.test.dao;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.cache.annotation.Cacheable;
import org.test.entity.TestTable;

import java.util.List;

@Mapper 
public interface TestTableDao {

      @Cacheable("testCache")
      List<TestTable> findAll();

      void insert (TestTable testTable);
}

第六步 测就完事了。

关于配置,网上搜了一个记录一下: https://www.cnblogs.com/mymelody/p/5618198.html

猜你喜欢

转载自blog.csdn.net/baitianmingdebai/article/details/85156958