积分排行榜
用 Sorted Set 保存用户编号与积分,按积分从高到低读取榜单。
数据结构
键 demo:ranking:points,成员是用户编号,score 是积分。
| 用户(ELEMENT) | 积分(SCORE) |
|---|---|
| u1002 | 20.25 |
| u1001 | 10.75 |
数据映射
ZRANGE ... WITHSCORES 返回 ELEMENT、SCORE 两列,一行映射为一个 RankEntry。
RankEntry.java
package com.example.redis;
import net.hasor.dbvisitor.mapping.Column;
public class RankEntry {
@Column("ELEMENT")
private String userId;
@Column("SCORE")
private Double points;
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Double getPoints() {
return this.points;
}
public void setPoints(Double points) {
this.points = points;
}
}
Mapper
PointsRankingMapper.java
package com.example.redis;
import java.util.List;
import net.hasor.dbvisitor.mapper.Param;
import net.hasor.dbvisitor.mapper.Query;
import net.hasor.dbvisitor.mapper.SimpleMapper;
@SimpleMapper
public interface PointsRankingMapper {
@Query("ZADD #{key} INCR #{points} #{userId}")
double addPoints(@Param("key") String key, @Param("userId") String userId,
@Param("points") double points);
@Query("ZRANGE #{key} 0 #{lastIndex} REV WITHSCORES")
List<RankEntry> top(@Param("key") String key, @Param("lastIndex") int lastIndex);
@Query("ZREVRANK #{key} #{userId}")
Long rank(@Param("key") String key, @Param("userId") String userId);
}