转自:

https://my.oschina.net/zb0423/blog/60957
http://www.cnblogs.com/fsjin/articles/3521261.html

Ehcache 是现在最流行的纯Java开源缓存框架,配置简单、结构清晰、功能强大。

  • 下载jar包 ehcache-core-2.3.0.jar
  • maven 仓库代理  https://repository.jboss.org/nexus/content/groups/developer/
  • 新搭建一个Maven项目
  • 配置jar包到pom文件中
  • 编写ehcache.xml缓冲配置文件 可以放在src的任何目录下

pom文件:

<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.lzyan.ehcache.demo</groupId>
<artifactId>EhcacheDemo</artifactId>
<version>v0.1</version>
<name>EhcacheDemo</name> <dependencies>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.6</version>
</dependency>
</dependencies> </project>

ehcache.xml文件:

<ehcache updateCheck="false" dynamicConfig="false">

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
its value in the running VM. The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path -->
<diskStore path="D:/tmp/test/ehcache"/> <cacheManagerEventListenerFactory class="" properties=""/> <!--Default Cache configuration. These will applied to caches programmatically created through
the CacheManager. The following attributes are required for defaultCache: maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.
-->
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="1200000"
timeToLiveSeconds="1200000"
overflowToDisk="true"
/> <cache name="icache-global"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
overflowToDisk="true"
/> <cache name="SimplePageCachingFilter"
maxElementsInMemory="10000"
maxElementsOnDisk="1000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU"
/>
</ehcache>

编写测试类:

import java.net.URL;
import java.util.concurrent.TimeUnit; import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element; public class EhCache_v2 { public static void main(String[] args) throws Exception {
System.out.println("main(): begin ...");
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource("ehcache.xml");
//创建一个缓存管理器
CacheManager manager = CacheManager.create(url);
String names[] = manager.getCacheNames();
System.out.println("Available caches list: \n---------");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
System.out.println("---------"); if(names.length > 0){
System.out.println("Selected_CacheName=" + names[0]);
}
Cache cache = manager.getCache(names[0]);
cache.put(new Element("name", "admin")); Element element = cache.get("name");
System.out.println("getValue()=" + element.getValue());
Object obj = element.getObjectValue();
System.out.println("getObjectValue()=" + obj); TimeUnit.SECONDS.sleep(3); ThreadAction action = new ThreadAction();
action.setCacheName(cache.getName());
action.setManager(manager);
action.start(); System.out.println("=== main thread is return! ===");
} } class ThreadAction extends Thread{
private String cacheName;
private CacheManager manager ; @Override
public void run() {
try {
Thread.sleep(3000);
Cache cache = manager.getCache(cacheName);
Element element = cache.get("name");
System.out.println("run(): 从缓存中取得数据:" + element.getObjectValue());
} catch (InterruptedException e) {
e.printStackTrace();
} } public CacheManager getManager() {
return manager;
}
public void setManager(CacheManager manager) {
this.manager = manager;
} public String getCacheName() {
return cacheName;
}
public void setCacheName(String cacheName) {
this.cacheName = cacheName;
} }

测试出缓存起作用:
需要设置配置文件中缓存名 name="SimplePageCachingFilter"  的存活时间

eternal="false"
timeToIdleSeconds="1"
timeToLiveSeconds="1"

不知道什么缓存管理器读取配置文件的规则,取出的 name[0]  是文件最后一个配置的缓存
然后再试运行 发现抛出空指针异常,说明从缓存中取不到数据了,说明这个测试可以测试出缓存是否起作用。

Demo2:

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element; public class EhCache { public static void main(String[] args) {
System.out.println("main(): begin ...");
// CacheManager manager = new CacheManager();
//创建一个缓存管理器
CacheManager singletonManager = CacheManager.create();
//建立一个缓存实例
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
//在内存管理器中添加缓存实例
singletonManager.addCache(memoryOnlyCache);
Cache cache = singletonManager.getCache("testCache");
//使用缓存
Element element = new Element("key1", "value1");
cache.put(element);
cache.put(new Element("key1", "value2")); element = cache.get("key1");
Object value = element.getObjectValue();
System.out.println(value); int elementsInMemory = cache.getSize();
System.out.println(elementsInMemory); long elementsInMemory2 = cache.getMemoryStoreSize();
System.out.println(elementsInMemory2); Object obj = element.getObjectValue();
cache.remove("key1");
System.out.println(obj);
singletonManager.shutdown();
// manager.shutdown();
System.out.println("main(): over ...");
} }

Ehcache Demo的更多相关文章

  1. 【Java】:ehcache

    ehcache是一个纯Java进程内缓存框架,是hibernate默认的Cacheprovider.(出自百度百科). 1. 快速2. 简单3. 多种缓存策略4. 缓存数据有两级:内存和磁盘,因此无需 ...

  2. Java SpringBoot使用Redis缓存和Ehcache

    <?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http:// ...

  3. springboot+ehcache 基于注解实现简单缓存demo

    1.加入maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactI ...

  4. springmvc 多数据源 SSM java redis shiro ehcache 头像裁剪

    获取下载地址   QQ 313596790  A 调用摄像头拍照,自定义裁剪编辑头像 B 集成代码生成器 [正反双向](单表.主表.明细表.树形表,开发利器)+快速构建表单;  技术:31359679 ...

  5. (转)springMVC+mybatis+ehcache详细配置

    一. Mybatis+Ehcache配置 为了提高MyBatis的性能,有时候我们需要加入缓存支持,目前用的比较多的缓存莫过于ehcache缓存了,ehcache性能强大,而且位各种应用都提供了解决方 ...

  6. spring缓存Ehcache(入门2)

    使用Ehcache缓存工具类. 一.由于使用了maven,所以需要引入依赖包: <dependency> <groupId>net.sf.ehcache</groupId ...

  7. 缓存插件 EHCache

    EHCache是来自sourceforge(http://ehcache.sourceforge.net/)的开源项目,也是纯Java实现的简单.快速的Cache组件. 下载jar包 Ehcache ...

  8. ehcache 分布式集群同步数据实例

    本文使用rmi方式,借鉴百度能搜到的文章,但是均不能做到数据同步,做了些改动完全没问题,更详细说明介绍百度即可.直奔主题,可运行的demo实例! 创建一个maven项目,配置pom pom.xml & ...

  9. ehcache集群的配置

    一:配置环境 本文是在测试demo的基础上写的,服务器包括申请的两台服务器和本机,共三台服务器.demo的目标是实现三台服务器之间共享cache. 申请的两台服务器地址分别是172.19.100.15 ...

随机推荐

  1. Dictionary读取键值的快捷方法

    对泛型集合Dictionary<T,T> 进行读取键值是经常的操作,一般情况下,都是通过keys 和values进行键值的读取操作: eg: foreach (var item in di ...

  2. 史上最简单,一步集成侧滑(删除)菜单,高仿QQ、IOS。

    重要的话 开头说,not for the RecyclerView or ListView, for the Any ViewGroup. 本控件不依赖任何父布局,不是针对 RecyclerView. ...

  3. C实现栈和队列

    这两天再学习了数据结构的栈和队列,思想很简单,可能是学习PHP那会没有直接使用栈和队列,写的太少,所以用具体代码实现的时候出现了各种错误,感觉还是C语言功底不行.栈和队列不论在面试中还是笔试中都很重要 ...

  4. Java集合框架实现自定义排序

    Java集合框架针对不同的数据结构提供了多种排序的方法,虽然很多时候我们可以自己实现排序,比如数组等,但是灵活的使用JDK提供的排序方法,可以提高开发效率,而且通常JDK的实现要比自己造的轮子性能更优 ...

  5. PS 使用的常用命令

    本文记载一些简单的PS使用的命令 1. photoshop 画完矩形调整大小方法: a.画完矩形. b.按下Ctrl+T. c.拖边线上的小正方形就是了. 2. 画圆或者矩形时,按住shift 可以变 ...

  6. java单例模式详解

    饿汉法 饿汉法就是在第一次引用该类的时候就创建对象实例,而不管实际是否需要创建.代码如下: public class Singleton { private static Singleton = ne ...

  7. html学习第一天笔记

    语义化,让你的网页更好的被搜索引擎理解在这一章节我们要开始把网页中常用到的标签一 一向大家介绍,学习这一章节的时候要记住学习html标签过程中,主要注意两个方面的学习:标签的用途.标签在浏览器中的默认 ...

  8. 2016 ACM/ICPC Asia Regional Dalian Online(更新到五道题)

    1006 Football Games 这道题输入也很阴险!!! 这道题过题姿势最优雅的,不是if else if else if.那样很容易wa的. 如果没有平手选项, 赢得加一分的话, 可以用La ...

  9. Android之UI编程(二):表格布局

    表格布局(TableLayout)继承了LinearLayout,它的本质依然是线性布局管理器,表TableLayout采用行.列的形式来管理UI组件,它并不需要明确地声明暴行多少行.多少列,而是通过 ...

  10. Shell 编程基础之 && 与 ||

    一.引言 Shell 在执行某个命令的时候,会返回一个返回值,该返回值保存在 shell 变量 $? 中.当 $? == 0 时,表示执行成功:当 $? == 1 时,表示执行失败.有时候,下一条命令 ...