【发布时间】:2018-05-20 11:53:00
【问题描述】:
我有更新点燃缓存记录的代码逻辑,
缓存定义为:
IgniteCache<String, TreeMap<Long, InfoResultRecord>> txInfoCache;
键是缓存类型字符串,对于值,我使用 TreeMap 来保持记录有序(我需要对数据进行排序),但是用于更新的时间随着 TreeMap 大小的增加而增加,我发现的是当 TreeMap 大小在 10K 左右时,每次调用一条记录添加到缓存值 treemap 非常慢,大约 2 秒,如果我有 1K 数据需要添加到 Treemap,它将花费 2000 秒,它真的很慢而不是可以接受。
我使用调用来更新缓存以将记录添加到 Treemap:
txInfoCache.invoke(txType, new TxInfoProcessor(), record);
缓存的配置是:
CacheConfiguration<String, TreeMap<Long, InfoResultRecord>> cacheCfg =
new CacheConfiguration<>("TxInfoCache");
cacheCfg.setCacheMode(CacheMode.REPLICATED);
//cacheCfg.setStoreKeepBinary(true);
cacheCfg.setAtomicityMode(ATOMIC);
cacheCfg.setBackups(0);
txInfoCache = ignite.getOrCreateCache(cacheCfg);
向Treemap添加记录的处理器是:
private static class TxInfoProcessor implements EntryProcessor<
String,
TreeMap<Long, InfoResultRecord>,
TreeMap<Long, InfoResultRecord>> {
@Override
public TreeMap<Long, InfoResultRecord> process(
MutableEntry<String,
TreeMap<Long, InfoResultRecord>> entry, Object... args) {
InfoResultRecord record = (InfoResultRecord) args[0];
final Long oneDayMsSeconds = 24 * 60 * 60 * 1000L;
TreeMap<Long, InfoResultRecord>
InfoResultRecordTreeMap = entry.getValue();
if (InfoResultRecordTreeMap == null) {
InfoResultRecordTreeMap = new TreeMap<>();
}
InfoResultRecordTreeMap.put(record.getDealTime() + oneDayMsSeconds, record);
entry.setValue(InfoResultRecordTreeMap);
return null;
}
}
有什么问题吗?还是我以错误的方式使用缓存?
我还编写了一个简单的测试代码来验证使用 TreeMap 获取/放置时的速度:
public class Server2 {
public static void main(String[] args) throws IgniteException {
try (Ignite ignite = Ignition.start("server-start.xml")) {
IgniteCache<String, TreeMap<Long, String>> testCache = ignite.getOrCreateCache("testCache");
testCache.put("my",new TreeMap<>());
while (true) {
StopWatch stopWatch = new StopWatch();
stopWatch.start("1");
TreeMap<Long, String> map = testCache.get("my");
stopWatch.stop();
stopWatch.start("2");
map.put(System.currentTimeMillis(),String.valueOf(new Random().nextInt(1000000000)));
testCache.put("my",map);
stopWatch.stop();
System.out.println("cacheSize:"+map.size()+","+stopWatch.prettyPrint());
}
}
}
}
cacheSize:1000,StopWatch '': running time (millis) = 195
-----------------------------------------
ms % Task name
-----------------------------------------
00080 041% 1
00115 059% 2
cacheSize:1001,StopWatch '': running time (millis) = 38
-----------------------------------------
ms % Task name
-----------------------------------------
00028 074% 1
00010 026% 2
cacheSize:3000,StopWatch '': running time (millis) = 139
-----------------------------------------
ms % Task name
-----------------------------------------
00055 040% 1
00084 060% 2
cacheSize:3001,StopWatch '': running time (millis) = 68
-----------------------------------------
ms % Task name
-----------------------------------------
00042 062% 1
00026 038% 2
它清楚地显示了当 Treemap 大小增加时,ignite cache get/put 消耗的时间增加,我认为这应该是 1~2ms,但这里是 xx ms,随着大小的增加,它会增加到 xxxms 甚至几秒。
【问题讨论】: