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的值就是总数。