利用spring redis的RedisTemplate进行分页:
场景:
现有项目若干,根据项目的创建时间(createTime)进行降序读取:
存储结构:
key:proList(list)
存放项目id
[
110,
111,
112
]
key:proInfo:{proId}(hash)
pro:110
{
id:110,
proName:p110,
createTime:"2019:01:03 04:23:35"
}
pro:111
{
id:111,
proName:p1111,
createTime:"2019:01:03 04:24:56"
}
pro:112
{
id:112,
proName:p112,
createTime:"2019:01:03 04:25:35"
}
分页方法:
public static <T> List<T> sortPageList(String key, String subKey, String by, boolean isDesc, boolean isAlpha, int off, int num) throws Exception {
SortQueryBuilder<String> builder = SortQueryBuilder.sort(key);
builder.by(subKey + "*->" + by);
builder.get("#");
builder.alphabetical(isAlpha);
if (isDesc)
builder.order(SortParameters.Order.DESC);
builder.limit(off, num);
List<String> cks = redisTemplate.sort(builder.build());
List<T> result = new ArrayList<T>();
for (String ck : cks) {
//得到项目对象 by(subKey+ck);
}
return result;
}
调用方法:
sortPageList("proList","pro:","createTime",true,false,0,20)//本次分页取前20条数据0-->19
需要注意到的是isAlpha参数
如果设置为true
将按照字幕顺序进行排序。