spring boot 使用Ehcache

1-引入maven依赖;

2-增加ehcache.xml

3-bootstrap.yml配置ehcache.xml的路径

4-启动类加注解@EnableCaching

5-使用处加注解@Cacheable("testCache")

1-引入maven依赖

        <!--spring boot 缓存支持启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <!--Ehcahe-->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.1</version>
        </dependency>

2-增加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">

    <!-- 磁盘缓存位置 -->
    <diskStore path="java.io.tmpdir/ehcache"/>

    <!-- 默认缓存 -->
    <defaultCache
            maxEntriesLocalHeap="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxEntriesLocalDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <cache name="testCache"
           maxElementsInMemory="1000"
           eternal="false"
           timeToIdleSeconds="3"
           timeToLiveSeconds="3"
           maxEntriesLocalDisk="10000000"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="LRU"/>
</ehcache>

3-bootstrap.yml配置ehcache.xml的路径

#ehcache
spring.cache.ehcache.config: ehcache.xml

4-启动类加注解@EnableCaching

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

5-使用处加注解@Cacheable("testCache")

    @GetMapping(value = "/testEhcache")
    @ResponseBody
    @Cacheable("testCache")
    public int testEhcache(int num) {
        logger.info("入参:" + num);
        logger.info("执行:" + num);
        for (int i = 0, n = num; i < n; i++) {
            num += i;
        }
        logger.info("结果:" + num);
        return num;
    }

    @GetMapping(value = "/testEhcache2")
    @ResponseBody
    @Cacheable("testCache")
    public int testEhcache2(int num) {
        logger.info("入参:" + num);
        logger.info("执行:" + num);
        for (int i = 0, n = num; i < n; i++) {
            num += Math.random() * 10;
        }
        logger.info("结果:" + num);
        return num;
    }

猜你喜欢

转载自www.cnblogs.com/chenglc/p/10715417.html