【Java】ehcache | EhCache | 集成缓存EhCache

一、说明

        1、maven项目

        2、SpringBoot项目

二、解决方案

1、引入依赖

<!--ehcache-->
<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>ehcache</artifactId>
	<version>2.8.3</version>
</dependency>

2、增加配置文件

1)位于resources根目录

2)示例图

3)ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="cache" updateCheck="false">

    <!-- 磁盘缓存位置 -->
    <diskStore path="java.io.tmpdir"/>

    <defaultCache eternal="false" maxElementsInMemory="1000"
		overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="3600"
		timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LRU" />

	<!-- 手动指定的缓存策略 -->
	<!-- 对不同的数据,缓存策略可以在这里配置多种 -->
	<!--sys-ku,库管理-->
	<!--
        diskStore path:用来配置磁盘缓存使用的物理路径
        name:   缓存名称,cache的唯一标识(ehcache会把这个cache放到HashMap里)
        eternal="false"   元素是否永恒,如果是就永不过期(必须设置)
        maxElementsOnDisk====磁盘缓存中最多可以存放的元素数量,0表示无穷大
        maxElementsInMemory="1000" 内存缓存中最多可以存放的元素数量(必须设置)
        timeToIdleSeconds="0"   导致元素过期的访问间隔(秒为单位). 0表示可以永远空闲,默认为0
        timeToLiveSeconds="600" 元素在缓存里存在的时间(秒为单位). 0 表示永远存在不过期
        overflowToDisk="false"  当缓存达到maxElementsInMemory值是,是否允许溢出到磁盘(必须设置)
        diskPersistent="false"  磁盘缓存在VM重新启动时是否保持(默认为false)
        diskExpiryThreadIntervalSeconds="100" 磁盘失效线程运行时间间隔,默认是120秒
        memoryStoreEvictionPolicy="LFU" 内存存储与释放策略.当达到maxElementsInMemory时
               共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)默认使用"最近使用"策略
    -->
	<cache
			name="sys"
			eternal="false"
			maxElementsInMemory="1000"
			overflowToDisk="false"
			diskPersistent="false"
			timeToIdleSeconds="300"
			timeToLiveSeconds="0"
			memoryStoreEvictionPolicy="LRU" />

</ehcache>
	

3、增加配置类

package hg.demo.spring.boot.web.ehcache;

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 EhCacheConfig {
	@Bean
	public EhCacheManagerFactoryBean cacheManagerFactoryBean(){
		EhCacheManagerFactoryBean bean = new EhCacheManagerFactoryBean();
		bean.setConfigLocation(new ClassPathResource("ehcache.xml"));
		bean.setShared(true);
		return bean;
	}
	@Bean
    public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){
      return new EhCacheCacheManager(bean.getObject());
    }	
}

 4、封装工具类

package hg.demo.spring.boot.web.ehcache;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Component;

/**
 * @author hgSuper
 * @date 2021-10-14
 */
@Slf4j
@Component("ehCacheUtils")
public class EhCacheUtils {
    @Autowired
    EhCacheCacheManager ehCacheCacheManager;

    /**
     * 设值
     * @param cacheName 策略名
     * @param key
     * @param val json
     */
    public void set(String cacheName, String key, String val) {
        log.info("set(),ehcache-设值,cacheName:{}", cacheName);
        log.info("set(),ehcache-设值,key:{}", key);
        log.info("set(),ehcache-设值,val:{}", val);
        ehCacheCacheManager.getCache(cacheName).put(key, val);
    }

    /**
     * 查询
     * @param cacheName
     * @param key
     * @return
     */
    public String get(String cacheName, String key) {
        log.info("get(),ehcache-查询,cacheName:{}", cacheName);
        log.info("get(),ehcache-查询,key:{}", key);
        String val = ehCacheCacheManager.getCache(cacheName).get(key, String.class);
        log.info("get(),ehcache-查询,val:{}", val);
        return val;
    }

    /**
     * 删除
     * @param cacheName
     * @param key
     */
    public void remove(String cacheName, String key) {
        log.info("remove(),ehcache-删除,cacheName:{}", cacheName);
        log.info("remove(),ehcache-删除,key:{}", key);
        ehCacheCacheManager.getCache(cacheName).evict(key);
    }

    /**
     * 清空
     * @param cacheName
     */
    public void clear(String cacheName) {
        log.info("remove(),ehcache-清空,cacheName:{}", cacheName);
        ehCacheCacheManager.getCache(cacheName).clear();
    }
}

5、注解方式

1)@Cacheable

作用:在查询时,会先从缓存中获取,若不存在才再发起对数据库的访问。

@Cacheable(value="策略名,配置在ehcache.xml",key="'key_'+#id")

 说明1: key,不支持枚举,支持静态常量

 说明2: #id,即入参变量名,类型可以是对象,调用 【"#id" -> "#bean.name"】

2)@CacheEvict

作用:通常用在删除方法,用来从缓存中移除相应数据

@CacheEvict(value = "策略名,配置在ehcache.xml", key = "")

3)@CachePut

作用:用于数据新增和修改操作上,用于更新缓存。

@CachePut(value = "策略名,配置在ehcache.xml", key = "")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java Ehcache是一个纯Java的进程内缓存框架,具有快速、精干等特点。它支持内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。Ehcache最初是由Greg Luck于2003年开始开发,截止目前,Ehcache已经演进到了3.10.0版本,各方面的能力已经构建的非常完善。Ehcache官网上也毫不谦虚的描述自己是“Java's most widely-used cache”,即JAVA中使用最广泛的缓存。 使用Ehcache可以提高应用程序的性能,减少数据库访问次数,提高响应速度。Ehcache可以用于缓存任何类型的对象,包括POJO、Hibernate对象、Spring对象等。Ehcache还支持缓存的过期时间、缓存的最大元素数、缓存的持久化等功能。 以下是一个使用Ehcache的例子: ```java import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; public class EhcacheDemo { public static void main(String[] args) { // 创建缓存管理器 CacheManager cacheManager = CacheManager.create(); // 创建缓存对象 Cache cache = new Cache("myCache", 10000, false, false, 5, 2); // 添加缓存对象到缓存管理器 cacheManager.addCache(cache); // 添加元素到缓存 Element element = new Element("key1", "value1"); cache.put(element); // 获取缓存中的元素 Element result = cache.get("key1"); System.out.println(result.getObjectValue()); // 关闭缓存管理器 cacheManager.shutdown(); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值