SpringBoot集成Ehcache实现缓存

SpringBoot集成Ehcache非常方便,也很简单,只需要以下简单4步即可实现Ehcache缓存。

第一步,增加两个依赖包

		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>

        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>

第二步,增加ehcache.xml配置

<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="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"/>

    <cache
            name="book"
            eternal="false"
            maxElementsInMemory="5000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="1800"
            memoryStoreEvictionPolicy="LRU"/>

</ehcache>

ehcache.xml配置参数说明:
共三种标签:diskStore、defaultCache、cache
1、diskStore标签配置说明

属性名属性值说明属性含义
pathuser.home – 用户主目录缓存路径
pathuser.dir – 用户当前工作目录缓存路径
pathjava.io.tmpdir – 默认临时文件路径缓存路径

2、defaultCache标签配置说明

属性名属性值说明属性含义
maxElementsInMemory缓存最大数目
maxElementsOnDisk硬盘最大缓存个数
eternaltrue、false对象是否永久有效,设置为true时,timeout将不起作用
overflowToDisktrue、false当系统宕机时是否保存到磁盘
timeToIdleSeconds默认值是0,可闲置时间无穷大设置对象在失效前的允许闲置时间(单位:秒)。当eternal=false时使用。可选属性
timeToLiveSeconds默认值:0,对象存活时间无穷大设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。当eternal=false时使用
diskPersistent默认为false虚拟机重启时,是否持久化数据到磁盘
diskSpoolBufferSizeMB默认是30MB设置DiskStore(磁盘缓存)的缓存区大小,每个Cache都有自己的一个缓冲区
diskExpiryThreadIntervalSeconds默认是120秒磁盘失效线程运行时间间隔
memoryStoreEvictionPolicy默认策略是LRU(最近最少使用)当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存 ,三种策略:FIFO、LFU、LRU
clearOnFlush内存数量最大时是否清除

FIFO:first in first out,先进先出。
LFU:Less Frequently Used,最少被使用。缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU:Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
3、 cache标签配置说明
cache标签属性包括了defaultCache中的属性,但多一个name属性,name属性是缓存名称,对应@Cacheable注解中的value。

第三步,Ehcache注入Bean,编写EhcacheConfiguration类,如下:

package com.sam.study.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
@EnableCaching
public class EhcacheConfiguration {

    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
        EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("/config/ehcache.xml"));
        return ehCacheManagerFactoryBean;
    }

    @Bean
    public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean ehCacheManagerFactoryBean) {
        EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager(ehCacheManagerFactoryBean.getObject());
        return ehCacheCacheManager;
    }
}

第四步,配置@Cacheable注解,service类代码示例如下:

package com.sam.study.service;

import com.github.pagehelper.PageHelper;
import com.sam.study.bean.Book;
import com.sam.study.dao.BookMapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class BookServiceImpl implements IBookService {

    @Resource
    private BookMapper bookMapper;

    @Cacheable(value = "book")
    public List<Book> findAllBook(int pageNum, int pageSize) {
        System.out.println("findAllBook...................");
        PageHelper.startPage(pageNum, pageSize);
        Iterable<Book> iterable = bookMapper.selectAll();
        List<Book> bookList = new ArrayList<>();
        iterable.forEach(book -> bookList.add(book));
        return bookList;
    }


    @Override
    @Cacheable(value = "book", key = "#id")
    public Book findBookById(int id) {
        System.out.println("findBookById从数据库查询:" + id);
        return bookMapper.selectById(id);
    }

}

以上四步即实现ehcache缓存。

最后,补充@Cacheable注解的两个基本属性说明:
1、cacheNames和value
这两个属性都是指定缓存的名字,通过源码可以看出将返回结果放在哪个缓存中,可以指定多个缓存。
在这里插入图片描述
2、key
缓存数据使用的key,它是用来指定对应的缓存,可以模拟使用方法参数值作为key的值,也可以使用SpEL表达式的值来指定。
在这里插入图片描述

名称描述示例
methodName被调用的方法名称#root.methodName
Method被调用的方法#root.method.name
Target当前被调用的目标对象#root.target
targetClass当前被调用的目标对象类#root.targetClass
args被调用方法的参数列表root.args[0]
caches调用的缓存列表root.caches[0].name
argument name方法的参数名称,可以直接使用#参数名#id,#name等等
result执行方法后的返回值#result

也可以通过以下方式查看root object对象有哪些:
在这里插入图片描述
本文主要是分享SpringBoot集成Ehcache实现缓存的基本使用。关于@Cacheable注解的深入探讨,后续再另写博文分享。谢谢!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值