Redis的sorted set集合提供了一种有序的集合,集合中的每个元素都会关联一个double类型的分数。redis正是通过分数来为集合中的成员进行从小到大的排序。
使用场景通常是作为排名。
在上一篇说了选择题型题目表设计,接着这篇说下用户回答题目后的排行设计,这里使用redis的有序集合进行排名,排名条件是正确率高,耗时少。
有序集合添加元素时需设定一个分数,这里两个排序条件不同,一个按照正确率倒序,一个按照耗时升序,所以需要设计一个分数计算算法。
这里通过位运算进行计算分数,将正确率*100后左移32位,再用Integer.MAX_VALUE-耗时(毫秒),将两者结果进行或运算,这样,正确率越高,耗时越少,分数越高,再反向排名即可。
demo使用springboot框架
redis客户端使用redisson;
orm使用mybatis
model
package com.example.demo.model;
import lombok.Data;
import java.util.Date;
@Data
public class Question {
private Long id;
private String title;
private Date createAt;
private Long createBy;
private Integer status;
private Date updateAt;
private Long updateBy;
}
package com.example.demo.model;
import lombok.Data;
import java.util.Date;
@Data
public class QuestionAnswer {
private Long id;
private Long userId;
private Long questionId;
private Long optionId;
private Long historyId;
private Integer status;
private Date updateAt;
private Long updateBy;
private Date createAt;
private Long createBy;
}
package com.example.demo.model;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class QuestionAnswerHistory implements Serializable {
private Long id;
private Long userId;
private Boolean answerFinish;
private Double correctRate;
private Integer timeConsumed;
private Integer status;
private Date createAt;
private Long createBy;
private Integer createAtMillisecond;
private Date updateAt;
private Long updateBy;
private Integer updateAtMillisecond;
private Integer timeConsumedMillisecond;
}
package com.example.demo.model;
import lombok.Data;
import java.util.Date;
@Dat