springmvc+ehcache详解

本文详细介绍了Ehcache的结构设计,包括CacheManager、Cache和Element的属性。阐述了Ehcache在Spring中的整合配置,如缓存初始化、动态创建缓存工具类的实现。此外,还提供了Ehcache监控的步骤,包括下载、配置和启动监控服务,帮助开发者更好地管理和优化缓存性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ehcache介绍

Ehcache是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider(hibernate-ehcache )。当然也可以和mybatis(mybatis-ehcache)结合,它具有内存和磁盘存储,ehcache直接在jvm虚拟机中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便,如果大规模集群还是考虑用memcached或redis。如果是单个应用或者对缓存访问要求很高的应用,用ehcache。


ehcache结构设计图

这里写图片描述

CacheManager:缓存管理器,一般单例模式,当然也可以多个实例,里面主要存放各个缓存区域Cache
Cache:所有cache都实现了Ehcache接口,类似一个HashMap,里面存放着各种键值对element,每个cache都可以设置存活时间,访问间歇时间等。
element:单条缓存数据的组成单位,由key和value组成

Cache的元素的属性
  1. name:缓存名称。
  2. maxElementsInMemory:缓存最大个数。
  3. eternal:对象是否永久有效,一但设置了,timeout将不起作用。
  4. timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
  5. timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
  6. overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中
  7. diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
  8. maxElementsOnDisk:硬盘最大缓存个数。
  9. diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
  10. diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
  11. memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
  12. clearOnFlush:内存数量最大时是否清除。
spring结合ehcache

1、配置所需的相关jar包

<!--缓存start-->
<!--ehcache缓存核心包-->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.6.9</version>
        </dependency>
        <!--做ehcache监控用的,mvn仓库里没有需要下载ehcache
的监控插件ehcache-monitor-kit-1.0.3,从里面提供的lib复制出来,后面会有相关介绍-->
        <dependency>
            <groupId>org.terracotta</groupId>
            <artifactId>ehcache-probe</artifactId>
            <version>1.0.3</version>
        </dependency>
        <!--spring注解对ehcache的操作-->
        <dependency>
            <groupId>com.googlecode.ehcache-spring-annotations</groupId>
            <artifactId>ehcache-spring-annotations</artifactId>
            <version>1.2.0</version>
        </dependency>
  <!--end-->

2、配置ehcache和spring结合时的相关配置文件,ehcache.xsd下载地址

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">
    <!-- 默认缓存配置. 自动失效:最后一次访问时间间隔300秒失效,若没有访问过自创建时间600秒失效。-->
    <defaultCache maxEntriesLocalHeap="1000"
                  eternal="false"
                  timeToIdleSeconds="300"
                  timeToLiveSeconds="600"
                  overflowToDisk="true"
                  statistics="true"/>

    <!-- 系统缓存 -->
    <cache name="sysCache" maxEntriesLocalHeap="1000"
           eternal="true"
           overflowToDisk="true"
           statistics="true"/>

    <!-- 用户缓存 -->
    <cache name="userCache"
           maxEntriesLocalHeap="1000"
           eternal="true"
           overflowToDisk="true"
           statistics="true"/>
<!--配置ehcache缓存监控的相关地址,端口-->
    <cacheManagerPeerListenerFactory
            class="org.terracotta.ehcachedx.monitor.probe.ProbePeerListenerFactory"
            properties="monitorAddress=localhost, monitorPort=9889,
            memoryMeasurement=true" />

</ehcache>

springmvc对ehcache的初始化配置

<?xml version="1.0" encoding="UTF-8"?>
<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.2.xsd">
<!-- 启用缓存注解功能-->
    <cache:annotation-driven cache-manager="ehcacheManager"/>

<!-- 基于spring实现的缓存管理器-->
    <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager"  ref="cacheManagerFactory"/>
    </bean>

  <!--加载ehcache的相关配置-->
    <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:cache/ehcache.xml"/>
    </bean>

<!--创建工具类ApplicationUtil,以便普通class根据bean id动态获取spring管理的bean-->
    <bean id="applicationUtil" class="com.personal.core.utils.ApplicationUtil"></bean>


</beans>

3、实现动态获取bean的工具类ApplicationUtil

package com.personal.core.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 注释
 *
 * @author: coding99
 * @Date: 16-11-24
 * @Time: 下午8:05
 */
public class ApplicationUtil implements ApplicationContextAware{

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationUtil.applicationContext = applicationContext;
    }

    public static Object getBean(String name){
        return applicationContext.getBean(name);
    }

}

5、实现动态创建cache缓存块的工具类EHCacheUtils

package com.personal.core.utils;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.cache.ehcache.EhCacheCacheManager;

import java.util.List;

/**
 * 注释
 *
 * @author: coding99
 * @Date: 16-11-24
 * @Time: 下午8:03
 */
public class EHCacheUtils {

    private static CacheManager cacheManager = null;

    static {
        EHCacheUtils.initCacheManager();
    }

    /**
     * 初始化缓存管理容器
     * @return
     */
    public static CacheManager initCacheManager() {

        try{
            if(cacheManager == null) {
                EhCacheCacheManager ehCacheCacheManager = (EhCacheCacheManager)ApplicationUtil.getBean("ehcacheManager");
                cacheManager = ehCacheCacheManager.getCacheManager();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return cacheManager;

    }

    /**
     * 初始化内存块
     * @param cacheName
     * @param maxElementsInMemory
     * @param overflowToDisk
     * @param eternal
     * @param timeToIdleSeconds
     * @param timeToLiveSeconds
     * @return
     */
    public static Cache initCache(String cacheName,int maxElementsInMemory,boolean overflowToDisk,boolean eternal,long timeToLiveSeconds,long timeToIdleSeconds) {

        Cache cache = cacheManager.getCache(cacheName);

        try {

            if(null == cache) {
                cache = new Cache(cacheName,maxElementsInMemory,overflowToDisk,eternal,timeToLiveSeconds,timeToIdleSeconds);
                cacheManager.addCache(cache);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return cache;

    }

    /**
     * 初始化内存块
     * @param cacheName
     * @param timeToIdleSeconds
     * @param timeToLiveSeconds
     * @return
     */
    public static Cache initCache(String cacheName,long timeToLiveSeconds,long timeToIdleSeconds) {

        return initCache(cacheName, EHCacheConfig.MAX_ELEMENTS_IN_MEMORY, EHCacheConfig.OVER_FLOW_TO_DISK,
                EHCacheConfig.ETERNAL,timeToLiveSeconds,timeToIdleSeconds);

    }



    /**
     * 移除缓存
     * @param cacheName
     */
    public static void removeCache(String cacheName) {
        checkCacheManager();
        Cache cache = cacheManager.getCache(cacheName);
        if(null != cache) {
            cacheManager.removeCache(cacheName);
        }
    }


    /**
     *
     * 获取所有的cache名称
     *
     * @return
     */

    public static String[] getAllCaches() {
        checkCacheManager();
        return cacheManager.getCacheNames();
    }

    /**
     * 移除所有cache
     */

    public static void removeAllCache() {
        checkCacheManager();
        cacheManager.removalAll();
    }

    /**
     * 初始化缓存
     *
     * @param cacheName
     * @return
     */
    public static Cache initCache(String cacheName) {

        checkCacheManager();
        if(null == cacheManager.getCache(cacheName)) {
            cacheManager.addCache(cacheName);
        }
        return cacheManager.getCache(cacheName);

    }



    /**
     * 添加缓存
     * @param cache 缓存块
     * @param key 关键字
     * @param value 值
     */
    public static void put(Cache cache,Object key, Object value) {
        checkCache(cache);
        Element element = new Element(key,value);
        cache.put(element);
    }


    /**
     * 获取值
     * @param cache 缓存块
     * @param key
     * @return
     */
    public static Object get(Cache cache,Object key) {
        checkCache(cache);
        Element element = cache.get(key);
        if(null ==  element) {
            return  null;
        }
        return element.getObjectValue();
    }

    /**
     * 移除key
     * @param cache 缓存块
     * @param key
     */
    public static void remove(Cache cache,String key) {
        checkCache(cache);
        cache.remove(key);
    }

    /**
     * 移除所有元素
     * @param cache 缓存块
     */
    public static void removeAllKey(Cache cache) {
        checkCache(cache);
        cache.removeAll();
    }

    /**
     * 获取 所有的key
     * @param cache 缓存块
     * @return
     */
    public static List getKeys(Cache cache) {
        checkCache(cache);
        return cache.getKeys();
    }


    /**
     * 检测内存管理器是否初始化
     */
    private static void checkCacheManager() {
        if(null == cacheManager) {
            throw new IllegalArgumentException("调用前请先初始化CacheManager值:EHCacheUtil.initCacheManager");
        }
    }

    /**
     * 检查内存块是否存在
     * @param cache
     */
    private static void checkCache(Cache cache) {
        if(null == cache) {
            throw new IllegalArgumentException("调用前请先初始化Cache值:EHCacheUtil.initCache(参数)");
        }
    }


    /**
     *
     * @param args
     */
    public static void main(String[] args) {

        Cache cache1 = EHCacheUtils.initCache("cache1", 60, 30);
        EHCacheUtils.put(cache1, "A", "a");
        Cache cache2 = EHCacheUtils.initCache("cache2", 50, 20);
        EHCacheUtils.put(cache2, "A", "b");

        System.out.println(EHCacheUtils.cacheManager.getCache("cache1"));
        System.out.println(EHCacheUtils.cacheManager.getCache("cache2"));
        System.out.println(EHCacheUtils.cacheManager.getCache("sysCache"));
        System.out.println(EHCacheUtils.cacheManager.getCache("userCache"));

    }

}
package com.personal.core.utils;

/**
 * 注释
 *
 * @author: coding99
 * @Date: 16-11-24
 * @Time: 下午8:03
 */
public class EHCacheConfig {

    //元素最大数量
    public static final int MAX_ELEMENTS_IN_MEMORY = 1000;
    //是否把溢出数据持久化到硬盘
    public static final boolean OVER_FLOW_TO_DISK = true;
    //是否会死亡
    public static boolean ETERNAL = false;
    //缓存间歇时间
    public static final int TIME_TO_IDLE_SECONDS = 300;
    //缓存存活时间
    public static final int TIME_TO_LIVE_SECONDS = 600;
    //是否需要持久化到硬盘
    public static final boolean DISK_PERSISTENT = false;
    //内存存取策略
    public static String MEMORY_STORE_EVICTION_POLICY = "LRU";

}

6、基于spring注解的的ehcache的用法
使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。下面是几个使用参数作为key的示例

  • @Cacheable可作用与类或者方法上,主要用于把返回的数据存入相应的缓存块里
  • @CacheEvict主要用于在方法执行前或者执行后清除指定缓存块里的相应元素
  • 相关属性请百度相应的用法
  @Cacheable(value="userCache", key="#id")

   public User find(Integer id) {

      returnnull;

   }


   @Cacheable(value="userCache", key="#p0")

   public User find(Integer id) {

      returnnull;

   }


   @Cacheable(value="userCache", key="#user.id")

   public User find(User user) {

      returnnull;

   }



   @Cacheable(value="userCache", key="#p0.id")

   public User find(User user) {

      return null;

   }

    @Cacheable({"cache1", "cache2"})//Cache是发生在cache1和cache2上的

   public User find(Integer id) {

      return null;

   } 

  @CacheEvict(value="userCache", beforeInvocation=true)

   public void delete(Integer id) {

      System.out.println("delete user by id: " + id);

   } 
ehcache监控

监控 ehcache缓存:

1.下载地址

2.解压缩到目录下,复制ehcache-monitor-kit-1.0.0\lib\ehcache-probe-1.0.0.jar到项目里面,如上面的通过pom.xml文件引入等方式

3.将以下配置copy的ehcache.xml文件的ehcache标签中

<cacheManagerPeerListenerFactory
    class="org.terracotta.ehcachedx.monitor.probe.ProbePeerListenerFactory"
    properties="monitorAddress=localhost, monitorPort=9889" />

如果有提示报错,请对properties里面的元素做换行或者空格处理,具体也不知道为啥

4.在\ehcache-monitor-kit-1.0.0\etc\ehcache-monitor.conf中可以配置监控的ip和端口号。
如把相应的#去掉

5.删除 startup.bat中的行 -j %PRGDIR%\etc\jetty.xml
启动被监控的web application和ehcache-monitor-kit-1.0.0\bin目录下的startup.bat(在windows环境下)

6.在浏览器中输入 http://localhost:9889/monitor/即可开始监控。
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值