spring-boot-ehcache-demo

本地缓存其实项目中用得还比较多,常用的ehcache,现整合spring-boot搭建一个demo方便以后查阅。

依赖包

下面2个依赖是spring-boot整合ehcache必须的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    <version>${spring-boot.version}</version>
</dependency>
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.3</version>
</dependency>

如果启用spring-boot单元测试,还需要加入下面的依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <version>${spring-boot.version}</version>
    <scope>test</scope>
</dependency>

配置

application.properties中指明ehcache配置文件

spring.cache.jcache.config=ehcache.xml

ehcache.xml配置ehcache缓存,具体配置项的意义请参考。
http://blog.csdn.net/clj198606061111/article/details/41121437

<?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/ehcache"/>

    <!-- default cache -->
    <defaultCache
            maxElementsInMemory="1000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"/>

    <!--自定义缓存配置-->
    <cache name="countries"
           maxElementsInMemory="1000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="LRU">
    </cache>

</ehcache>

启用缓存

在spring-boot启动类加上@EnableCaching注解,表明该项目启用缓存。

@EnableCaching
@EnableScheduling
@SpringBootApplication
public class ItcljApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder().sources(ItcljApplication.class)
                .profiles("app").run(args);
    }

}

使用缓存

使用缓存其实很简单,只需要在缓存的方法上加上@Cacheable注解即可,@CacheEvict@CachePut等缓存相关注解另行查询其他资料。

@Component
@CacheConfig(cacheNames = "countries")
public class CountryRepository {

    @Cacheable(key = "'country'+#code")
    public Country findByCode(String code) {
        System.out.println("---> Loading country with code '" + code + "'");
        return new Country(code);
    }

}

原文地址:http://www.itclj.com/blog/58bd2a4447508f786718d4f4
项目地址:https://github.com/clj198606061111/spring-boot-ehcache-demo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值