java中redis分页获取所有数据
解决方法:
假如redis的数据结构是hash类型,现在500条获取一次直到获取完所有数据
1.核心方法
public static Map<String, String> hscan(int dbIndex,String key,int pageSize){
Map<String, String> map = new HashMap<String, String>();
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.select(dbIndex);
ScanParams sp = new ScanParams();
sp.count(pageSize);//每次多少条
loop(map, key, jedis, "0", sp);
} catch (Exception e) {
log.error(e.getMessage());
return null;
}finally{
// 返还到连接池
if(jedis!=null)returnResource(jedisPool, jedis);
}
return map;
}
public static Map<String, String> loop(Map<String, String> mapList, String key, Jedis jedis, String cursor,
ScanParams sp) {
try {
ScanResult<Entry<String, String>> map = jedis.hscan(key, cursor, sp);
cursor = map.getStringCursor();
for (Entry<String, String> en : map.getResult()) {
mapList.put(en.getKey(), en.getValue());
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (!"0".equals(cursor)) {
loop(mapList, key, jedis, cursor, sp);
}
return mapList;
}
2.使用方法:
hscan(0,"rd_table",500);其中0是数据库下标,rd_table是表名
其中jedisPool获取请参考:http://yayihouse.com/yayishuwu/chapter/1361