广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring整合ehCache全过程
  • 421
分享到

Spring整合ehCache全过程

Spring整合ehCacheSpring ehCache 2023-02-14 18:02:01 421人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录1. 基本介绍2. 主要的特性3. 集成4. ehcache 和 Redis 比较5. ehcache 与 spring整合①. pom.xml 引入spring和ehcache

1. 基本介绍

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认Cache方式。

Ehcache是一种广泛使用的开源Java分布式缓存。

它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序等特点。

Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Ehcache),但本身不直接提供缓存功能的实现。它支持注解方式使用缓存,非常方便。

2. 主要的特性

  • 1、快速
  • 2、简单
  • 3、多种缓存策略
  • 4、缓存数据有两级:内存和磁盘,因此无需担心容量问题
  • 5、缓存数据会在虚拟机重启的过程中写入磁盘
  • 6、可以通过RMI、可插入api等方式进行分布式缓存

3. 集成

可以单独使用,一般在第三方库中被用到的比较多(如mybatisshiro等)。

ehcache 对分布式支持不够好,多个节点不能同步,通常和redis一块使用。

一般使用ehcache做本地缓存,解决Redis单点压力过大等问题。

4. ehcache 和 redis 比较

  • ehcache直接在JVM虚拟机中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便。
  • redis是通过Socket访问到缓存服务,效率比ecache低,比数据库要快很多。
  • ehcache也有缓存共享方案,不过缓存共享复杂,维护不方便;

5. ehcache 与 Spring整合

①. pom.xml 引入spring和ehcache

<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>
  <groupId>com.mengdee</groupId>
  <artifactId>ehcache</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <junit.version>4.10</junit.version>
    <spring.version>4.2.3.RELEASE</spring.version>
  </properties>
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-test</artifactId>
         <version>${spring.version}</version>
         <scope>test</scope>
     </dependency>
    
    
    <!-- springframework -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-WEBmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>
    
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>2.10.3</version>
    </dependency>
 
    
  </dependencies>
  
  <repositories>
    <repository>
        <id>aliyun</id>
        <name>aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
    </repository>
  </repositories>
</project>

②applicationContext.xml中引入ehcache配置

<!-- ehcache配置 -->
<import resource="classpath*:conf/spring/ehcache-mamage.xml" />

③ehcache-mamage.xml 配置文件

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">
 
    <!-- 启用缓存注解开关 -->
    <cache:annotation-driven />
 
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcacheManager"/>
    </bean>
 
    <!-- ehCache 配置管理器 -->
    <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:conf/ehcache.xml" />
        <!--true:单例,一个cacheManager对象共享;false:多个对象独立 -->
        <property name="shared" value="true" />
    </bean>
</beans>

④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" updateCheck="false">
    <!--
        name:缓存区名称,用以区别缓存区,必须唯一
        maxEntriesLocalHeap:设置缓存在本地内存中最大缓存项数量,0表示无限,等效于旧版本中的maxElementsInMemory属性
        eternal:设置缓存项是否为永久的。如果设置为true,缓存项的过期设置将被忽略,缓存项永不过期
        timeToIdleSeconds:设置一个缓存项在过期前的闲置时间。即一个缓存项在其过期前,两次访问间隔的最大时间。仅在缓存项为非永久时有效。0表示不限闲置时间,默认为0
        timeToLiveSeconds:设置一个缓存项在过期前的生存时间。即从缓存项创建到过期的最大时间。仅在缓存项为非永久时有效。0表示不限生存时间,默认为0
        overflowToDisk:当内存中对象数量达到maxEntriesLocalHeap时,Ehcache将会对象写到磁盘中
        copyOnRead:当缓存项被读出时,是否返回一份它的拷贝(返回对象是缓存中对象的拷贝)。默认false
        copyOnWrite:当缓存项被写入时,是否写入一份它的拷贝(写入缓存的是写入对象的拷贝)。默认false
        memoryStoreEvictionPolicy:当缓存项达到maxEntriesLocalHeap限制时,剔除缓存项的策略。默认为LRU(Least Recently Used)。
        其他的策略有:FIFO(First In First Out)和LFU(Less Frequently Used)
    -->
 
 
    <cache name="cmApplyInfoDataCache" maxEntriesLocalHeap="3600" timeToIdleSeconds="20" timeToLiveSeconds="86400"
           eternal="false" overflowToDisk="false" copyOnRead="true" copyOnWrite="true" memoryStoreEvictionPolicy="LRU">
        <searchable/>
        <persistence strategy="none"/>
    </cache>
 
</ehcache>

⑤测试EhCache缓存 java代码实现

 @RequestMapping("/testSpringEhCache.action")
    @ResponseBody
    public Map<String, Object> testSpringEhCache(httpservletRequest request) {
        Map<String, Object> params = baseController.getParams(request);
        String supplierCode = MapUtils.getString(params, "supplierCode", "");
        String productCode = MapUtils.getString(params, "productCode", "");
 
        CmpProductSingleCommonEntity entity = orderDataTempService.queryProductSingleCommon(supplierCode, productCode);
        return CmUtils.convertDTOToMap(entity);
    }
 @Override
    @Cacheable(value = "cmApplyInfoDataCache", key = "'cmp_cmApplyInfo_cache_key_'+#supplierCode+'_'+#productCode")
    public CmpProductSingleCommonEntity queryProductSingleCommon(String supplierCode, String productCode) {
        return cmpProductSingleCommonDAO.queryProductSingleCommon(supplierCode, productCode);
    }

5. Spring缓存标签

实现原理:

Spring对缓存的支持类似于对事务的支持。

首先使用注解标记方法,相当于定义了切点,然后使用aop技术在这个方法的调用前、调用后获取方法的入参和返回值,进而实现了缓存的逻辑。

①@Cacheable标签

表明所修饰的方法是可以缓存的:当第一次调用这个方法时,它的结果会被缓存下来,在缓存的有效时间内,以后访问这个方法都直接返回缓存结果,不再执行方法中的代码段。

这个注解可以用condition属性来设置条件,如果不满足条件,就不使用缓存能力,直接执行方法。

可以使用key属性来指定key的生成规则。

@Cacheable 支持如下几个参数:

  • value:缓存位置名称,不能为空,如果使用EHCache,就是ehcache.xml中声明的cache的name, 指明将值缓存到哪个Cache中
  • key:缓存的key,默认为空,既表示使用方法的参数类型及参数值作为key,支持SpEL,如果要引用参数值使用井号加参数名,如:#userId,

一般来说,我们的更新操作只需要刷新缓存中某一个值,所以定义缓存的key值的方式就很重要,最好是能够唯一,因为这样可以准确的清除掉特定的缓存,而不会影响到其它缓存值 ,

本例子中使用实体加冒号再加ID组合成键的名称,如"user:1"、"order:223123"等

  • condition:触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持SpEL

举例如下:

入参为单个字符串的场景:

// 将缓存保存到名称为UserCache中,键为"user:"字符串加上userId值,如 'user:1' 
 
    @Cacheable(value = "UserCache", key = "'user:' + #userId")
    public User findById(String userId) {
        return  new User("1", "mengdee");
    } 

入参为多个字符串的场景:

@Cacheable(value = "cmApplyInfoDataCache", key = "'cmp_cmApplyInfo_cache_key_'+#supplierCode+'_'+#productCode")
    public CmpProductSingleCommonEntity queryProductSingleCommon(String supplierCode, String productCode) {
        return cmpProductSingleCommonDAO.queryProductSingleCommon(supplierCode, productCode);
    }

入参为Map场景:

   @Cacheable(value="supplierInfoDataCache", key = "'params:'+#supplierCode")
    public List<Map<String, Object>> queryDataList(Map<String, Object> params) {
        return cmpProductSingleCommonDAO.querySupplierIsPublishCmBySupplierCode(params);
    }

②@CacheEvict标签

与@Cacheable功能相反,@CacheEvict表明所修饰的方法是用来删除失效或无用的缓存数据。

@CacheEvict 支持如下几个参数:

  • value:缓存位置名称,不能为空,同上
  • key:缓存的key,默认为空,同上
  • condition:触发条件,只有满足条件的情况才会清除缓存,默认为空,支持SpEL
  • allEntries:true表示清除value中的全部缓存,默认为false
//清除掉UserCache中某个指定key的缓存    
@CacheEvict(value="UserCache",key="'user:' + #userId")    
public void removeUser(User user) {    
    System.out.println("UserCache"+user.getUserId());    
}    
 
//清除掉UserCache中全部的缓存    
@CacheEvict(value="UserCache", allEntries=true)    
public final void setReservedUsers(String[] reservedUsers) {    
   System.out.println("UserCache deleteall");    
}

6. ehcache.xml 配置说明

  • name

缓存区名称,用以区别缓存区,必须唯一

  • maxEntriesLocalHeap

设置缓存在本地内存中最大缓存项数量,0表示无限,等效于旧版本中的maxElementsInMemory属性

  • eternal

设置缓存项是否为永久的。如果设置为true,缓存项的过期设置将被忽略,缓存项永不过期

  • timeToIdleSeconds

设置一个缓存项在过期前的闲置时间。即一个缓存项在其过期前,两次访问间隔的最大时间。仅在缓存项为非永久时有效。0表示不限闲置时间,默认为0

  • timeToLiveSeconds

设置一个缓存项在过期前的生存时间。即从缓存项创建到过期的最大时间。仅在缓存项为非永久时有效。0表示不限生存时间,默认为0

  • overflowToDisk

当内存中对象数量达到maxEntriesLocalHeap时,Ehcache将会对象写到磁盘中

  • copyOnRead

当缓存项被读出时,是否返回一份它的拷贝(返回对象是缓存中对象的拷贝)。默认false

  • copyOnWrite

当缓存项被写入时,是否写入一份它的拷贝(写入缓存的是写入对象的拷贝)。默认false

  • memoryStoreEvictionPolicy

当缓存项达到maxEntriesLocalHeap限制时,剔除缓存项的策略。默认为LRU(Least Recently Used)。

其他的策略有:FIFO(First In First Out)和LFU(Less Frequently Used)

实例:

   <cache name="cmApplyInfoDataCache" maxEntriesLocalHeap="3600" timeToIdleSeconds="20" timeToLiveSeconds="86400"
           eternal="false" overflowToDisk="false" copyOnRead="true" copyOnWrite="true" memoryStoreEvictionPolicy="LRU">
        <searchable/>
        <persistence strategy="none"/>
    </cache>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: Spring整合ehCache全过程

本文链接: https://www.lsjlt.com/news/196077.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作