码上敲享录 > redis数据库常见问题 > java中redis分页获取所有数据

java中redis分页获取所有数据

上一章章节目录下一章 2019-01-28已有3508人阅读 评论(0)

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

向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交