ehcache 简介和基本api使用

1.ehcahce简介  
在开发高并发量,高性能的网站应用系统时,缓存Cache起到了非常重要的作用。 
EHCache是来自sourceforge(http://ehcache.sourceforge.net/)的开源项目,也是 纯Java 实现的简单、快速的Cache组件。EHCache支持 内存和磁盘 的缓存,支持 LRU、LFU和FIFO 多种淘汰算法,支持 分布式 的Cache,可以作为Hibernate的缓存插件,是Hibernate中默认的CacheProvider。同时它也能提供基于Filter的Cache,该Filter可以缓存响应的内容并采用Gzip压缩提高响应速度。 

Ehcache缓存的特点:  
1. 快速. 
2. 简单. 
3. 多种缓存策略 
4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题 
5. 缓存数据会在虚拟机重启的过程中写入磁盘 
6. 可以通过RMI、可插入API等方式进行分布式缓存 
7. 具有缓存和缓存管理器的侦听接口 
8. 支持多缓存管理器实例,以及一个实例的多个缓存区域 
9. 提供Hibernate的缓存实现 

2.Ehcache缓存- 解读Ehcache配置文件ehcache.xml  
缓存的配置有很多选项,主要集中在ehcache.xml里。比如缓存的名称,监听器等。Ehcache提供了默认的配置文件。同时可以自己指定缓存,比如 
Java代码   收藏代码
  1. <diskStore path="D:/work2/renhewww/cache"/>   
  2. <cache name=" sampleCache1"   
  3.       maxElementsInMemory="1"   
  4.            maxElementsOnDisk="10000"   
  5.            eternal="false"   
  6.            overflowToDisk="true"   
  7.            diskSpoolBufferSizeMB="20"   
  8.            diskPersistent="true"   
  9.            timeToIdleSeconds="43200"   
  10.            timeToLiveSeconds="86400"   
  11.            memoryStoreEvictionPolicy="LFU"   
  12.         />   

各配置参数的含义: 
name :Cache的唯一标识 
maxElementsInMemory :缓存中允许创建的最大对象数 
eternal :缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。 
timeToIdleSeconds :缓存数据的钝化时间,也就是在一个元素消亡之前,两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是 0 就意味着元素可以停顿无穷长的时间。 
timeToLiveSeconds :缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。 
overflowToDisk :内存不足时,是否启用磁盘缓存。 
memoryStoreEvictionPolicy :缓存满了之后的淘汰算法。LRU和FIFO算法这里就不做介绍。LFU算法直接淘汰使用比较少的对象,在内存保留的都是一些经常访问的对象。对于大部分网站项目,该算法比较适用。 
如果应用需要配置多个不同命名并采用不同参数的Cache,可以相应修改配置文件,增加需要的Cache配置即可。

3.Ehcache缓存的使用  
3.1 安装ehcache 
Ehcache 的特点,是一个纯Java ,过程中(也可以理解成插入式)缓存实现,单独安装Ehcache ,需把ehcache-X.X.jar 和相关类库方到classpath中。如项目已安装了Hibernate ,则不需要做什么,直接可以使用Ehcache 。 

如果使用maven,可以在pom.xml里配置: 
    
Java代码   收藏代码
  1. <dependency>  
  2.           <groupId>net.sf.ehcache</groupId>  
  3.           <artifactId>ehcache</artifactId>  
  4.           <version>2.9.0</version>  
  5.       </dependency>  


3.2 生成CacheManager 
使用CacheManager 创建并管理Cache大概步骤为: 
第一步:生成CacheManager对象 
第二步:生成Cache对象 
第三步:向Cache对象里添加由key,value组成的键值对的Element元素 
第四步:关闭CacheManager。 

1.创建CacheManager有4种方式:  
方式一:使用默认配置文件创建 
Ehcache有默认的配置文件ehcache.xml,里面有默认的配置和一个默认的缓存。
Java代码   收藏代码
  1. CacheManager manager = CacheManager.create();    


方式二:使用指定配置文件创建 
Java代码   收藏代码
  1. CacheManager manager = CacheManager.create("src/config/ehcache.xml");  
  

方式三:从classpath中找寻配置文件并创建 
Java代码   收藏代码
  1. URL url = getClass().getResource("/anothername.xml");    
  2. CacheManager manager = CacheManager.create(url);   


方式四:通过输入流创建 
Java代码   收藏代码
  1. InputStream fis = new FileInputStream(new File("src/config/ehcache.xml").getAbsolutePath());    
  2.   
  3. try  
  4. {    
  5.     manager = CacheManager.create(fis);    
  6. }   
  7. finally  
  8. {    
  9.     if (fis != null)  
  10.     {  
  11.         fis.close();  
  12.     }  
  13. }  

  
// 使用manager 移除 指定名称的Cache对象 
Java代码   收藏代码
  1. manager.removeCache("demoCache");  

可以通过调用manager.removalAll()来移除所有的Cache。 

2 创建Cache 
通过CacheManager创建Cache: 
Java代码   收藏代码
  1. Cache cache = manager.getCache("sampleCache1");  
  

3 利用cache存取数据  
存储数据 
Java代码   收藏代码
  1. Element element = new Element("key1""value1");     
  2. cache.put(new Element(element);     

Java代码   收藏代码
  1. 获取数据   

Element element = cache.get("key1"); 

/从Cache中 移除 一个元素 
Java代码   收藏代码
  1. cache.remove("key");   


注意:可以直接使用上面的API进行数据对象的缓存,这里需要注意的是对于缓存的对象都是必须可序列化的。  

4.缓存的关闭 
Java代码   收藏代码
  1. manager.shutdown();    


3.3 实例  
Java代码   收藏代码
  1. import net.sf.ehcache.Cache;  
  2. import net.sf.ehcache.CacheManager;  
  3. import net.sf.ehcache.Element;  
  4.   
  5. public class Ehcache  
  6. {  
  7.     public static void main(String[] args)  
  8.     {  
  9.         CacheManager manager = CacheManager.create("src/main/resources/conf/ehcache.xml");  
  10.         Cache cache = manager.getCache("sampleCache1");  
  11.         Element element = new Element("key","value");  
  12.         cache.put(element);  
  13.           
  14.         System.out.println(cache.get("key"));  
  15.           
  16.         manager.shutdown();  
  17. }  

输出:  
[ key = key, value=value, version=1, hitCount=1, CreationTime = 1414933551601, LastAccessTime = 1414933551601 ] 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Ehcache作为缓存的Spring Boot应用程序的示例: 1.添加Ehcache依赖项 在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> ``` 2.配置Ehcache 在application.properties文件中添加以下配置: ```properties spring.cache.type=ehcache ``` 3.创建缓存管理器 创建一个名为EhCacheConfig的类,并在其中创建一个名为cacheManager的方法,该方法返回一个CacheManager对象。 ```java @Configuration @EnableCaching public class EhCacheConfig { @Bean public CacheManager cacheManager() { return new EhCacheCacheManager(ehCacheManager().getObject()); } @Bean public EhCacheManagerFactoryBean ehCacheManager() { EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean(); factory.setConfigLocation(new ClassPathResource("ehcache.xml")); factory.setShared(true); return factory; } } ``` 4.创建缓存 在需要缓存的方法上添加@Cacheable注释,并指定缓存名称和缓存键。 ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Override @Cacheable(value = "users", key = "#id") public User getUserById(Long id) { return userRepository.findById(id).orElse(null); } } ``` 以上就是使用Ehcache作为缓存的Spring Boot应用程序的示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值