本文介绍EhCache查询缓存中数据,EhCache提供了类似Hibernate的查询API,可以按照给定的条件进行查询。
要对EhCache进行查询,需要在ehcache.xml中设定要查询的属性
数据准备
@Before
public void setUp() {
//加载EhCache配置文件
InputStream in = EhcacheTest.class.getClassLoader().getResourceAsStream("ehcache-query.xml");
CacheManager cm = CacheManager.create(in);
cache = cm.getCache("data-query");
Person p1 = new Person(1, "Tom", 34);
Person p2 = new Person(2, "Tom", 34);
Person p3 = new Person(3, "Jack", 32);
Person p4 = new Person(4, "Jack", 32);
//添加三个元素,Key是Person对象的ID
Element element = new Element(p1.getId(), p1);
cache.putIfAbsent(element);
element = new Element(p2.getId(), p2);
cache.putIfAbsent(element);
element = new Element(p3.getId(), p3);
cache.putIfAbsent(element);
//添加一个元素,Key和Value都是Person对象
cache.putIfAbsent(new Element(p4, p4));
}
1. 在上面的测试setup方法中,为缓存添加了四个元素。前三个以person的id作为key,最后一个以person对象本身作为key 2.四个person对象,有些数据是相同的,方便后面按照Value的指定属性进行查询
基本查询
对EhCache最基本的需求是对缓存元素的Key和Value进行查询,这在ehcache.xml中需要做如下配置
<cache> <searchable/> </cache>
searchable有两个可选属性,keys和values,它们的默认值都是true,即默认情况下,EhCache已经将Key和Value的查询添加上了,查询属性分别是key和value。上面的设置等价于
<cache>
<searchable keys="true" values="true"/>
</cache>
如果不允许针对keys或者values进行查询,将它置为false即可。
测试一:查询所有数据
//查询缓存中所有的数据
@org.junit.Test
public void test0() {
Query query = cache.createQuery();
Results results = query.includeKeys().includeValues().execute();
List<Result> resultList = results.all();
Assert.assertEquals(4, resultList.size());
}
测试二: 根据Key(简单类型查询)进行条件查询
//根据简单查询属性类型(Key是整型)进行查询
@org.junit.Test
public void test1() {
Query query = cache.createQuery();
query.includeKeys(); //查询结果中包含Key
query.includeValues(); //查询结果中包含Value
Attribute<Integer> attribute = cache.getSearchAttribute("key"); //按照EhCache内置的可查询属性key进行查询
query.addCriteria(attribute.eq(2)); //查询条件:key为2,2是简单类型
Results results = query.execute();
List<Result> resultList = results.all();
Result result = resultList.get(0);
Integer key = (Integer) result.getKey();
org.junit.Assert