我正在考虑使用 JBoss Cache 或 Ehcache 来实现缓存。在查看了这两个 API 之后,我直觉 JBoss 可能比 Ehcache 内存效率高一点,因为它可以将原始对象放入缓存中,而 Ehcache 需要将数据包装在一个Element
对象中。
我设置了一个快速工作台,在缓存中重复插入键、值元组。键和值类非常简单:
钥匙:
public class Key implements Serializable {
private static final long serialVersionUID = -2124973847139523943L;
private final int key;
public Key(int pValue) {
this.key = pValue;
}
public int getValue() {
return this.key;
}
@Override
public String toString() {
return "Key [key=" + this.key + "]";
}
}
价值:
public class Value implements Serializable{
/**
* serialVersionUID
*/
private static final long serialVersionUID = -499278480347842883L;
}
当插入 100000 个对象时,内存中的结果与我的预期完全一致,Ehcache 使用 13396 字节来存储对象,而 JBoss 使用 5712 字节进行相同的操作(这很好,因为相同的测试使用了ConcurrentHashMap
5680 字节)。
然而,当我查看执行时间时,我有一个非常糟糕的惊喜:Ehcache 用了 300 毫秒来执行我的测试,而 JBossCache 用了 44 秒来做同样的事情。我很确定我的 JBoss 配置中有一些烂东西可以解释这种差异。
Ehcache 是这样以编程方式初始化的:
CacheConfiguration cacheConfiguration = new CacheConfiguration("MyCache", 0).diskPersistent(false).eternal(true)
.diskExpiryThreadIntervalSeconds(100000).transactionalMode(TransactionalMode.OFF);
final Configuration config = new Configuration();
config.setDefaultCacheConfiguration(cacheConfiguration);
this.cacheManager = new CacheManager(config);
cacheConfiguration.name("primaryCache");
this.cache = new net.sf.ehcache.Cache(cacheConfiguration);
this.cacheManager.addCache(this.cache);
JBoss 缓存是使用 Spring 使用以下 bean 配置创建的:
<bean id="cache" class="org.jboss.cache.Cache" factory-bean="cacheFactory" factory-method="createCache">
<constructor-arg>
<value type="java.io.InputStream">/META-INF/jbossCacheSimpleConf.xml</value>
</constructor-arg>
</bean>
和以下jbossCacheConf.xml
文件:
<?xml version="1.0" encoding="UTF-8"?>
<jbosscache xmlns="urn:jboss:jbosscache-core:config:3.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:jboss:jbosscache-core:config:3.2 http://www.jboss.org/schema/jbosscache/jbosscache-config-3.2.xsd">
</jbosscache>
为了完整起见,Ehcache 测试是:
for (int i = 0; i < ITEM_COUNT; i++) {
this.cache.put(new Element(new Key(i), new Value()));
}
而 JBoss 之一是:
for (int i = 0; i < ITEM_COUNT; i++) {
this.processNode.put(new Key(i), new Value());
}
我的设置/基准有什么问题吗?