java redis 实现分页查询key pattern列表

Redis实现分页功能代码:

public List<String> findKeysForPage(String patternKey, int pageNum, int pageSize) {
    ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();
    RedisConnectionFactory factory = stringRedisTemplate.getConnectionFactory();
    RedisConnection rc = factory.getConnection();
    Cursor<byte[]> cursor = rc.scan(options);
    List<String> result = new ArrayList<String>(pageSize);
    int tmpIndex = 0;
    int startIndex = (pageNum - 1) * pageSize;
    int end = pageNum * pageSize;
    while (cursor.hasNext()) {
      if (tmpIndex >= startIndex && tmpIndex < end) {
        result.add(new String(cursor.next()));
        tmpIndex++;
        continue;
      }
 
      // 获取到满足条件的数据后,就可以退出了
      if(tmpIndex >=end) {
          break;
      }
 
      tmpIndex++;
      cursor.next();
    }
 
    try {
      // cursor.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
 
    try {
      RedisConnectionUtils.releaseConnection(rc, factory);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }

1.能分页获取key的列表

2.如果需要获取总数,去掉上面方法中

  // 获取到满足条件的数据后,就可以退出了
      if(tmpIndex >=end) {
          break;
      }

最终的tmpIndex的值就是总数。

猜你喜欢

转载自blog.csdn.net/qq_36189144/article/details/88351489