缓存--ehcache3的基本使用

http://www.ehcache.org/documentation/3.7/getting-started.html   --cache3.7官方英文文档  怎么使用这里写的都很明白

https://www.cnblogs.com/zhao1949/p/8124325.html   springboot与ehcache3整合

https://www.jianshu.com/p/0a24a6ced3b9  springboot与ehcache3整合

ehcache3 和 ehcache2 完全是两个框架

 

导入包、需要有slf4j包的支持

<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.7.1</version>
</dependency>

Demo例子基本使用

其用法类似于使用map进行缓存,ehcache3帮我们封装了缓存策略、对象的序列化、硬盘文件io、持久化。使用者只需在配置好之后当成一个map使用。

package a.caixl.cache;

import java.io.File;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.UserManagedCache;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.builders.UserManagedCacheBuilder;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.impl.config.persistence.CacheManagerPersistenceConfiguration;

public class EhcacheDemo {

	public static void main(String[] args) {
		
		CacheManager cacheManager = 
				CacheManagerBuilder.newCacheManagerBuilder()
/**1**/		.with(new CacheManagerPersistenceConfiguration(new File("D:"+ File.separator + "myData")))
/**2**/		//.withCache("preConfigured",  cBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))) 
				.build();
		
		cacheManager.init(); 
		
		/**解释
		 * CacheManager 由 静态的newCacheManagerBuilder创建
		 * 标记1:创建的时候可以绑定0-N个配置,使用with方法。如要使用硬盘缓存则必须指定存储地址
		 * 标的2:可初始就创建0-N个缓存,注意指定其别名,
		 * 创建缓存必须设定其CacheConfiguration
		 * **/
//		Cache<Long, String> preConfigured =  cacheManager.getCache("preConfigured", Long.class, String.class); 

		/**创建一个缓存,设定其配置 。 可以给 CacheConfiguration 绑定 缓存时效的配置 **/
		Cache<Long, String> myCache = cacheManager.createCache("myCache", 
		    CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, 
		    		ResourcePoolsBuilder.heap(10)  //堆内大小
		    		.offheap(2,MemoryUnit.MB )  //堆外大小
		    		.disk(1, MemoryUnit.GB)   //硬盘缓存大小
		    		)
//		    		.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(10)))		
		    );

		myCache.put(1L, "da one!"); 
		String value = myCache.get(1L); 
		System.out.println(value);
		
//		cacheManager.removeCache("preConfigured"); 

		cacheManager.close(); 
	}
}

ehcache3提供3种缓存方式
注意缓存的对象必须是实现了序列化接口,非堆内的缓存使用是序列化存储、反序列化读取。

堆内缓存:缓存在JVM中,也是最高效的并被GC管理的。
堆外缓存:缓存在JVM之外的内存中,通过对象系列化的方式缓存。  效率低于堆内缓存,比硬盘缓存快。
硬盘缓存:物理硬盘

实际的测试,缓存读取的速度非常快,读取硬盘缓存也是很快的。


使用xml配置得到CacheManager

<?xml version="1.0" encoding="UTF-8"?>

<config
    xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns='http://www.ehcache.org/v3'
    xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd">

  <!-- 指定硬盘存储目录,如用不到硬盘缓存,无需设置 -->
  <persistence directory="D:/dataDir" />

  <cache alias="foo"> 
    <key-type>java.lang.String</key-type> 
    <value-type>java.lang.String</value-type> 
    <resources>
      <heap unit="entries">20</heap> 
      <offheap unit="MB">1</offheap> 
      <disk persistent="true" unit="MB">500</disk>
    </resources>
  </cache>

  <!-- cache-template  创建公开配置,被继承用 -->
  <cache-template name="myDefaults"> 
    <key-type>java.lang.Long</key-type>
    <value-type>java.lang.String</value-type>
    <heap unit="entries">200</heap>
  </cache-template>

  <!-- 继承自myDefaults,并重写其参数 -->
  <cache alias="bar" uses-template="myDefaults"> 
    <key-type>java.lang.Number</key-type>
  </cache>

  <cache alias="simpleCache" uses-template="myDefaults" /> 

</config>
package a.caixl.cache;

import java.net.MalformedURLException;
import java.net.URL;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.Configuration;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.xml.XmlConfiguration;

public class EhcacheXmlDemo {
	public static void main(String[] args) throws MalformedURLException {
		URL myUrl =EhcacheXmlDemo.class.getResource("/ehcache-config.xml");
		Configuration xmlConfig = new XmlConfiguration(myUrl); 
		CacheManager myCacheManager = CacheManagerBuilder.newCacheManager(xmlConfig); 
		myCacheManager.init(); //注意需要进行初始化
		
		Cache<String, String> foo = myCacheManager.getCache("foo", String.class, String.class); 
		
		Cache<Number, String> bar = myCacheManager.getCache("bar", Number.class, String.class); 
		
		Cache<Long, String> simpleCache = myCacheManager.getCache("simpleCache", Long.class, String.class); 
		
		System.out.println(foo);
		System.out.println(bar);
		System.out.println(simpleCache);
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
jeesuite-libs分布式架构开发套件。包括缓存(一二级缓存、自动缓存管理)、队列、分布式定时任务、文件服务(七牛、阿里云OSS、fastDFS)、日志、搜索、代码生成、API网关、配置中心、统一认证平台、分布式锁、分布式事务、集成dubbo、spring boot支持、统一监控等。所有release版都经过严格测试并在生产环境稳定运行4年+。 功能列表: cache模块 基于配置支持单机、哨兵、分片、集群模式自由切换 更加简单的操作API封装 一级缓存支持(ehcache & guava cache)、分布式场景多节点自动通知 多组缓存配置同时支持 (一个应用多个redis server) 分布式模式开关 kafka模块 基于spring封装简化配置和调用方式 基于配置新旧两版Consumer API兼容支持 支持二阶段处理,即:fetch线程同步处理和process线程异步处理 消费成功业务处理失败自动重试或自定义重试支持 process线程池采用LinkedTransferQueue,支持线程回收和队列大小限制,确保系统崩溃等不会有数据丢失。 支持特殊场景发送有状态的消息(如:同一个用户的消息全部由某一个消费节点处理) producer、consumer端监控数据采集,由(jeesuite-admin)输出 兼容遗留kafka系统、支持发送和接收无封装的消息 mybatis模块 代码生成、自动CRUD、可无缝对接mybaits增强框架Mapper 基于properties配置多数据源支持,无需修改XML 读写分离,事务内操作强制读主库 基于注解自动缓存管理(所有查询方法结果自动缓存、自动更新,事务回滚缓存同步回滚机制) 自动缓存实现基于jeesuite-cache和spring-data-redis 分页组件 敏感操作拦截 scheduler模块 支持分布式保证单节点执行(按节点平均分配job) 支持failvoer,自动切换故障节点 支持多节点下并行计算 支持无注册中心单机模式 支持自定义重试策略 支持配置持久化(启动加载、变更保存) 支持控制台(jeesuite-admin)任务监控、开停、动态修改调度时间策略、手动触发执行 jeesuite-security 配置简单(初始化一个类即可) 满足认证授权基本需求 更加贴近日常使用业务场景 可选本地session和共享session 可选是否支持多端同时登录 dubbo、springboot跨服务登录状态传递支持 rest模块 自动resonse封装(xml、json) i18n request、response日志记录 自动友好错误 校验框架 filesystem模块 七牛文件服务支持 阿里云OSS文件服务支持 fastDFS文件系统支持 支持spring集成 配置式切换服务提供商 common模块 一些常用工具类 common2模块(需要依赖一些组件或者基础设置) 分布式锁 分布式全局ID生成器 excel导入导出 jeesuite-springboot-starter模块 springboot集成支持
使用 Ehcache 缓存来配置 Spring Boot 的步骤如下: 1. 添加 Ehcache 依赖:在 pom.xml 文件中添加 Ehcache 的相关依赖。 ```xml <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> ``` 2. 创建 Ehcache 配置文件:在 src/main/resources 目录下创建一个 ehcache.xml 文件,并配置缓存的名称、容量、过期时间等信息。 ```xml <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ehcache.org/v3" xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd"> <cache alias="myCache"> <expiry> <ttl unit="seconds">60</ttl> </expiry> <heap unit="entries">100</heap> </cache> </config> ``` 3. 配置 Spring Boot 应用程序:在 Spring Boot 的配置类上使用 @EnableCaching 注解开启缓存功能,并指定 Ehcache缓存管理器。 ```java import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.ehcache.EhCacheCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableCaching public class CacheConfig { @Bean public EhCacheCacheManager cacheManager(CacheManager ehCacheManager) { return new EhCacheCacheManager(ehCacheManager); } } ``` 4. 使用缓存注解:在需要缓存的方法上使用 Spring 的缓存注解,比如 @Cacheable、@CachePut、@CacheEvict 等。 ```java @Service public class MyService { @Cacheable("myCache") public String getCachedData(String key) { // 从数据库或其他数据源中获取数据 return data; } } ``` 以上是使用 Ehcache 缓存配置 Spring Boot 的基本步骤。请根据你的具体需求进行相应的修改和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值