【EhCache一】EhCache版Hello World

首先到ehcache官网下载:ehcache官网

下载完后解压。

打开Myeclipse 创建web项目,然后在项目classpath根目录下创建ehchache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
    updateCheck="true" monitoring="autodetect"
    dynamicConfig="true">

    <defaultCache
       maxElementsInMemory="20"
       eternal="false"
       overflowToDisk="false"
       timeToIdleSeconds="1800"
       timeToLiveSeconds="1800">
    </defaultCache>

    <cache name="data-cache"
      maxElementsInMemory="20"
      overflowToDisk="false"
      eternal="false"
      timeToIdleSeconds="1800"
      timeToLiveSeconds="1800"
      memoryStoreEvictionPolicy="LRU"
      transactionalMode="off"
       >
   <searchable keys="true"/> <!--可以根据Key进行查询,查询的Attribute就是keys-->
    </cache>
</ehcache>

参数含义:

name:Cache的唯一标识,程序中使用这个名字获得缓存实例

maxElementsInMemory:内存中最大缓存对象数 。

overflowToDisk:当overflowToDisk配置为true,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中。

eternal:Element是否永久有效,一但设置了, timeToIdleSeconds和 timeToLiveSeconds 将不起作用

timeToIdleSeconds: Element在缓存中空闲的最大时间。也就是说,这个时间控制的是一个Element 在一直没有被访问的前提下,这个对象可以在cache中的存活时间。若是0,表示永远存活

timeToLiveSeconds: 设置对象在cache中的最大存活时间,就是 无论对象被访问或是闲置,这个对象在cache中总的存活时间。也就是说, timeToLiveSeconds的值得应该大于等于 timeToIdleSeconds, 若是0,表示永远存活。

memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内 存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)

maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大。 该选项只有在overflowToDisk为true时有效

diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区

EhCache CRUD例子

package com.mayi.ehcache.demo;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.search.Attribute;
import net.sf.ehcache.search.Query;
import net.sf.ehcache.search.Result;
import net.sf.ehcache.search.Results;
import org.junit.Assert;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;
import java.util.Set;

public class EhcacheTest {

    @Test
    public void testCacheManager() {
  //加载EhCache配置文件
  InputStream in = EhcacheTest.class.getClassLoader().getResourceAsStream("ehcache.xml");
  CacheManager cm = CacheManager.create(in);

  //列出所有的缓存名称,不包括配置文件中的<defaultCache>
  String[] names = cm.getCacheNames();

  //只有一个名称为data-cache的cache
  Assert.assertEquals(1, names.length);
  Assert.assertEquals(names[0], "data-cache");

  //根据指定名称查找缓存对象
  Cache cache = cm.getCache("data-cache"); //根据缓存名称获取缓存
  Assert.assertNotNull(cache);

  //获取,更新Cache配置的接口
//  CacheConfiguration configuration = cache.getCacheConfiguration();
//  configuration.setTimeToIdleSeconds(3600);

  //缓存在内存中的配置信息,缓存配置动态修改也会体现出来,
  System.out.println(cm.getActiveConfigurationText());

  //清除所有缓存的数据,但是缓存本身仍然存在
//  cm.clearAll();

  //从内存中删除一个缓存以及所有的数据,Cache被销毁
//  cm.removeCache("data-cache");


    }

    @Test
    public void testCache() {
  //只有被有初始化生效的Cache允许改名字
  //cache.setName("data-cache-changed");
    }

    @Test
    public void testAddElementToCache() {
  //加载EhCache配置文件
  InputStream in = EhcacheTest.class.getClassLoader().getResourceAsStream("ehcache.xml");
  CacheManager cm = CacheManager.create(in);

  Cache cache = cm.getCache("data-cache");

  Person p1 = new Person(1, "Jack", 21);
  Person p2 = new Person(2, "Mike", 73);

  cache.putIfAbsent(new Element(p1,p1, 1));
  cache.put(new Element(p2,p2, 1));
  cache.putIfAbsent(new Element(p2, p1,1));//只有Key为p2的数据不存在才插入

  //得到的是p2,而不是p1
  Element e = cache.get(p2);
  Assert.assertEquals(p2, e.getObjectValue());

  //把数据从内存刷到DiskStore,从DiskStore刷新到Disk中
  cache.flush();

    }

    @Test
    public void testRemoveElementFromCache() {
  //加载EhCache配置文件
  InputStream in = EhcacheTest.class.getClassLoader().getResourceAsStream("ehcache.xml");
  CacheManager cm = CacheManager.create(in);

  Cache cache = cm.getCache("data-cache");

  Person p1 = new Person(1, "Jack", 21);
  Person p2 = new Person(2, "Mike", 73);

  Element e1  = new Element(p1,p1, 1);
  cache.putIfAbsent(e1);
  Element e2 = new Element(p2,p2, 1);
  cache.put(e2);

  cache.remove(p1);
  boolean isSucc = cache.removeElement(e1);
  //e1已经被删除,因此操作返回false
  Assert.assertFalse(isSucc);

  cache.put(e1);

  cache.removeAll();

  Assert.assertEquals(0, cache.getSize());
    }

    @Test
    public void testUpdateElementInCache() {
  //加载EhCache配置文件
  InputStream in = EhcacheTest.class.getClassLoader().getResourceAsStream("ehcache.xml");
  CacheManager cm = CacheManager.create(in);

  Cache cache = cm.getCache("data-cache");

  Person p1 = new Person(1, "Jack", 21);
  Person p2 = new Person(2, "Mike", 73);

  Element e1  = new Element(p1,p1, 1);
  cache.putIfAbsent(e1);
  Element e2 = new Element(p2,p2, 1);
  cache.put(e2);

  e2 = new Element(p2, p1, 1);
  cache.replace(e2);

  Assert.assertEquals(p1, e2.getObjectValue());

    }

    @Test
    public void testQueryElementsFromCache() {
  InputStream in = EhcacheTest.class.getClassLoader().getResourceAsStream("ehcache.xml");
  CacheManager cm = CacheManager.create(in);
  Cache cache = cm.getCache("data-cache");

  //EhCache中的数据类型是Element,它包含Key,Value和一个版本信息
  Element e = new Element(1000, 10000, 1);
  cache.put(e);

  //添加第二个数据
  e = new Element(2000, 20000, 1);
  cache.put(e);

  //缓存中有两条数据
  Assert.assertEquals(2, cache.getSize());

  //通过get方法获得key对应的数据
  e = cache.get(1000);
  Assert.assertEquals(10000, e.getObjectValue());

  //创建查询
  Query q = cache.createQuery();

  //Cache没有配置任何查询属性,这里察看下默认的查询属性有哪些
  //set中包含两个可查询元素:key和value
  Set<Attribute> set = cache.getSearchAttributes();

  //属性是范型类,得到key都应的查询属性对象
  Attribute<Integer> keyAttribute = cache.getSearchAttribute("key"); //根据默认提供的可查询属性key进行查询

  //构造查询条件,这是一个链式写法,一个Query对象可以写多个查询条件
  //创建查找key的值为2000的查询
  q = q.addCriteria(keyAttribute.eq(2000));

  //如果不includeKeys和q.includeValues();,则测试结果集中不包括Keys和Values信息
  q.includeKeys();
  q.includeValues();

  //执行查询
  Results results = q.execute();//执行查询
  Assert.assertNotNull(results);
  Assert.assertEquals(results.size(), 1);

  //列出所有结果
  List<Result> resultList = results.all();
  Result result = resultList.get(0);
  Assert.assertEquals(2000, result.getKey());

  Assert.assertEquals(20000, result.getValue());
    }

}

Person 类

package com.mayi.ehcache.demo;

public class Person {
    private int id;
    private String name;
    private int age;

    public Person(int id, String name, int age) {
  this.id = id;
  this.name = name;
  this.age = age;
    }

    @Override
    public boolean equals(Object o) {
  if (this == o) return true;
  if (o == null || getClass() != o.getClass()) return false;

  Person person = (Person) o;

  if (age != person.age) return false;
  if (id != person.id) return false;
  if (name != null ? !name.equals(person.name) : person.name != null) return false;

  return true;
    }

    @Override
    public int hashCode() {
  int result = id;
  result = 31 * result + (name != null ? name.hashCode() : 0);
  result = 31 * result + age;
  return result;
    }
}

最后运行junit即可

案例下载:http://download.csdn.net/detail/caiwenfeng_for_23/8469925

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 确定你想要缓存的数据类型,然后创建一个名为`CacheConfig`的Java类。在这个类中,你需要使用`@Configuration`注解来标记它为配置类。 接下来,使用`@EnableCaching`注解启用缓存。 然后,你需要创建一个名为`ehCacheCacheManager`的bean,这个bean将负责管理你的缓存。 为了创建这个bean,你需要使用`CacheManagerBuilder`类中的`newCacheManagerBuilder`方法来构建一个新的`CacheManager`实例。 接下来,你需要使用`CacheConfigurationBuilder`类中的`newCacheConfigurationBuilder`方法来配置你的缓存。在这个方法中,你可以设置缓存的名称、数据类型、过期时间等参数。 最后,你可以使用`CacheManagerBuilder`类中的`build`方法来构建并返回一个新的`CacheManager`实例。 下面是一个示例代码: ```java @Configuration @EnableCaching public class CacheConfig { @Bean public CacheManager ehCacheCacheManager() { return CacheManagerBuilder .newCacheManagerBuilder() .withCache("myCache", CacheConfigurationBuilder .newCacheConfigurationBuilder(String.class, String.class, ResourcePoolsBuilder.heap(10)) .build()) .build(); } } ``` 在这个示例中,我们创建了一个名为`myCache`的缓存,它存储的是字符串类型的数据,并且使用堆内内存作为资源池,最大容量为10。 ### 回答2: ehcache3 是一个用于 Java 的开源缓存框架,用于提供高效的数据缓存解决方案。以下是一个示例的 ehcache3 配置类: ```java import org.ehcache.CacheManager; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import java.time.Duration; public class EhCacheConfig { public static CacheManager getCacheManager() { // 创建一个缓存配置 CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder( Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(100, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB) .disk(50, MemoryUnit.MB) ) .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMinutes(30))) .build(); // 创建一个缓存管理器并添加缓存配置 CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("exampleCache", cacheConfiguration) .build(true); return cacheManager; } public static void main(String[] args) { // 使用示例 CacheManager cacheManager = getCacheManager(); // 获取缓存 Cache<Long, String> cache = cacheManager.getCache("exampleCache", Long.class, String.class); // 添加数据到缓存 cache.put(1L, "Hello, World!"); // 从缓存中获取数据 String value = cache.get(1L); System.out.println(value); // 输出:Hello, World! // 关闭缓存管理器 cacheManager.close(); } } ``` 这个配置类中创建了一个名为 "exampleCache" 的缓存,并设置了最大堆内存、堆外内存和磁盘空间的限制。还设置了缓存数据的过期策略为最近访问时间超过30分钟后过期。使用缓存时,可以通过缓存管理器获取缓存,然后进行数据的读取和写入操作。最后,在不再需要缓存时,需要手动关闭缓存管理器。 注意:以上代码仅为示例,实际使用时需要根据具体需求进行配置。 ### 回答3: 以下是一个简单的ehcache3配置类的示例: ```java import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.jsr107.Eh107Configuration; import javax.cache.CacheManager; import javax.cache.Caching; import java.util.concurrent.TimeUnit; public class EhCacheConfig { public static void main(String[] args) { // 创建一个CacheManager CacheManager cacheManager = Caching.getCachingProvider().getCacheManager(); // 配置缓存的ExpiryPolicy,设置缓存的过期时间为5分钟 ExpiryPolicy<Object, Object> expiryPolicy = ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(5)); // 创建一个缓存的配置对象,并将ExpiryPolicy与CacheConfiguration关联 CacheConfiguration<Object, Object> cacheConfig = CacheConfigurationBuilder .newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder.heap(100)) .withExpiry(ExpiryPolicyBuilder.expiryPolicy(expiryPolicy)) .build(); // 通过CacheManagerBuilder创建一个CacheManager,并将缓存配置添加到CacheManager中 CacheManagerBuilder builder = CacheManagerBuilder.newCacheManagerBuilder(); builder = builder.withCache("myCache", Eh107Configuration.fromEhcacheCacheConfiguration(cacheConfig)); // 初始化CacheManager cacheManager = builder.build(); cacheManager.init(); // 从CacheManager中获取一个Cache对象 Cache<Object, Object> myCache = cacheManager.getCache("myCache", Object.class, Object.class); // 在缓存中存储一个键值对 myCache.put("key", "value"); // 从缓存中获取一个键的值 Object value = myCache.get("key"); // 打印输出值 System.out.println(value); // 关闭CacheManager cacheManager.close(); } } ``` 上述代码演示了如何配置一个基本的ehcache3缓存。它创建了一个CacheManager,设置了一个名为"myCache"的缓存,并配置了缓存的过期时间为5分钟。之后,在缓存中存储一个键值对,并从缓存中获取该键的值。最后,关闭CacheManager。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值