Redis 与 Java 静态变量缓存去读记录
Posted by 2017/5/8 15:32:43 • Author:JK.Li
测试数据:4198条的一个数据列表。
Redis采用Key Value 存储形式,直接缓存4198条的一个List对象。
下文说到的Code代表的是一个唯一的Key.
分别测试1000次、10000次读取耗时:
测试一:
通过Code获取对象,流程:从redis取出所有数据,遍历查找所需的数据,查询到后,放入redis,下次查找直接从redis返回:
public DictionaryDto getDictionaryByCode(String code) { DictionaryDto dictionaryDto = (DictionaryDto) setCacheKey(DICTIONARY_SINGLE_PREFIX + code).getCacheContent(); if (dictionaryDto == null) { dictionaryDto = getAll().stream().filter(t -> t.getCode().equals(code)).findFirst().get(); setCacheKey(DICTIONARY_SINGLE_PREFIX + code).setCacheContent(dictionaryDto).save(); } return dictionaryDto; }
耗时:4385ms,41728ms
测试二:
通过Code获取对象,流程:从redis取出所有数据放入静态变量,下次查找出在静态变量中遍历查询,不再连接redis:
private static List<DictionaryDto> tempList = null; public DictionaryDto getDictionaryByCode(final String code) { if(tempList == null){ tempList = getAll(); } return tempList.stream().filter(t -> t.getCode().equals(code)).findFirst().get(); }
耗时:229ms,307ms
测试三:
通过Code获取对象,流程:从redis取出所有数据放入静态变量Hashtable中:
private static Hashtable<String, DictionaryDto> tempHt = new Hashtable<>(); public DictionaryDto getDictionaryByCode(String code) { if (tempHt.containsKey(code)) { return tempHt.get(code); } else { DictionaryDto dictionaryDto = getAll().stream().filter(t -> t.getCode().equals(code)).findFirst().get(); tempHt.put(code, dictionaryDto); return dictionaryDto; } }
耗时:207ms,224ms
先把数据全部放入Hashtable中:
private static Hashtable<String, DictionaryDto> tempHt = null; public DictionaryDto getDictionaryByCode(String code) { if (tempHt == null) { tempHt = new Hashtable<>(); List<DictionaryDto> list = getAll(); for (DictionaryDto dictionaryDto : list) { tempHt.put(code, dictionaryDto); } } return tempHt.get(code); }
耗时:204ms,210ms
0 评论列表
发表评论
Wise Words
We can let circumstances rule us, or we can take charge and rule our lives from
within .
Earl Nightingale