ehcache

简述

EhCache 是一个纯Java的分布式的进程内缓存框架,具有快速、精干等特点,主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点,是Hibernate中默认的CacheProvider;

  • 在 Spring Boot中,通过@EnableCaching注解自动化配置合适的缓存管理器

  • 关于 Spring Boot 的缓存机制:
    高速缓存抽象不提供实际存储,并且依赖于由org.springframework.cache.Cache和org.springframework.cache.CacheManager接口实现的抽象。 Spring Boot根据实现自动配置合适的CacheManager,只要缓存支持通过@EnableCaching注释启用即可。

  • 特点
    (1)快速简单,具有多种缓存策略
    (2)缓存数据有两级为内存和磁盘,缓存数据会在虚拟机重启的过程中写入磁盘
    (3)可以通过RMI、可插入API等方式进行分布式缓存
    (4)具有缓存和缓存管理器的侦听接口
    (5)支持多缓存管理器实例,以及一个实例的多个缓存区域。并提供Hibernate的缓存实现
    (6)Ehcache有缓存共享方案,不过是通过RMI或者Jgroup多播方式进行广播缓存通知更新,缓存共享复杂,维护不方便;简单的共享可以,但是涉及到缓存恢复,大数据缓存,则不合适

环境搭建

  • 依赖
      <!--开启 cache 缓存-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-cache</artifactId>
      </dependency>
      <!-- ehcache 缓存 -->
      <dependency>
          <groupId>net.sf.ehcache</groupId>
          <artifactId>ehcache</artifactId>
      </dependency>
  • 配置文件(eccache.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">
   //默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
    <defaultCache
           //对象是否永久有效,一但设置了,timeout将不起作用。
            eternal="false"
            //内存缓存最大数目
            maxElementsInMemory="1000"
            //硬盘最大缓存个数
            maxElementsOnDisk="5000"
            //是否保存到磁盘,当系统宕机时
            overflowToDisk="false"
            //是否缓存虚拟机重启期数据
            diskPersistent="false"
            //设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
            timeToIdleSeconds="0"
            //设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
            timeToLiveSeconds="600"
            //当达到缓存最大值限制时,缓存清除策略
            memoryStoreEvictionPolicy="LRU" />

    <!-- 这里以example为例 -->
    <cache
            //缓存名称
            name="example"
            eternal="false"
            maxElementsInMemory="100"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="300"     
            memoryStoreEvictionPolicy="LRU" />
</ehcache>

diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。 

项目使用

  • springboot支持的注解
    1:@Cacheable : Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。
    2:@CacheEvict : 清除缓存。
    3: @CachePut : @CachePut也可以声明一个方法支持缓存功能。使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
  • 这三个方法中都有两个主要的属性:value 指的是 ehcache.xml 中的缓存策略空间(name属性);key 指的是缓存的标识,同时可以用 # 来引用参数。

与其他缓存比较

  • ehcache和redis有什么区别
    前者操作简单易使用,存取速度快,效率更高但是不适合大型的分布式集群部署。而后者更适合用于大数据缓存,数据恢复等。

结合springboot

1:pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ramostear</groupId>
    <artifactId>cache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>cache</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--Spring Boot应用程序提供缓存支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--提供了Ehcache的缓存实现-->
        <dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>
         <!--提供了基于JSR-107的缓存规范-->
        <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2:配置

spring.cache.jcache.config=classpath:ehcache.xml

然后使用@EnableCaching注解开启Spring Boot应用程序缓存功能(启动类上)。
3:书写ehcache.xml,同上面介绍。
4:还需要定义个缓存事件监听器,用于记录系统操作缓存数据的情况,最快的方法是实现CacheEventListener接口:

@Slf4j
public class PersonCacheEventLogger implements CacheEventListener<Object,Object>{



    @Override
    public void onEvent(CacheEvent cacheEvent) {
        log.info("person caching event {} {} {} {}",
                cacheEvent.getType(),
                cacheEvent.getKey(),
                cacheEvent.getOldValue(),
                cacheEvent.getNewValue());
    }
}

5:使用@Cacheable注解

@Service
public class PersonService {

    @Cacheable(cacheNames = "person",key = "#id")
    public Person getPerson(Long id){
        Person person = new Person(id,"ramostear","ramostear@163.com");
        return person;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值