点赞排行榜(ZSET实现)
实现原理:
使用redis的zset进行存储,score为当前时间,值为用户ID
public Result likeBlog(Long id) {
// 1.获取登录用户
Long userId = UserHolder.getUser().getId();
// 2.判断当前登录用户是否已经点赞
String key = BLOG_LIKED_KEY + id;
Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
if (score == null) {
// 3.如果未点赞,可以点赞
// 3.1.数据库点赞数 + 1
boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
// 3.2.保存用户到Redis的set集合 zadd key value score
if (isSuccess) {
stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
}
} else {
// 4.如果已点赞,取消点赞
// 4.1.数据库点赞数 -1
boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
// 4.2.把用户从Redis的set集合移除
if (isSuccess) {
stringRedisTemplate.opsForZSet().remove(key, userId.toString());
}
}
return Result.ok();
}
获取点赞排行榜前5名
String key = BLOG_LIKED_KEY + id;
// 1.查询top5的点赞用户 zrange key 0 4
Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
if (top5 == null || top5.isEmpty()) {
return Result.ok(Collections.emptyList());
}
// 2.解析出其中的用户id
List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
String idStr = StrUtil.join(",", ids);
// 3.根据用户id查询用户 WHERE id IN ( 5 , 1 ) ORDER BY FIELD(id, 5, 1)
List<UserDTO> userDTOS = userService.query()
.in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list()
.stream()
.map(user -> BeanUtil.copyProperties(user, UserDTO.class))
.collect(Collectors.toList());
// 4.返回
return Result.ok(userDTOS);
MySQL中的Field函数
field() 函数:是将查询的结果集按照指定顺序排序。
格式: FIELD(str,str1,str2,str3,...)
什么时候用: 想让某几个特定的字段值放在最后,用field()函数。
解释: str是字段名字,字符串str1,str2,str3等等,是该字段的值。
函数意思: 匹配到str1,将其放到结果集最后返回。
详细解析: 当字段值没有匹配到str1,str2或者str3的时候,按照正常排序;当匹配到这些的时候,会把没有匹配的值放到最前面,匹配到的放到后边,并且以写的顺序排序返回结果集。
场景: 数据库有字段model,代表手机型号,值有很多,和更多型号;现在根据model字段排序,查询结果集中,’‘更多型号’’ 必须放最后。
ORDER BY FIELD(model,'更多型号')
1
sql中排序比较常见,我们常用的排序语句是这两个。
select * from 表名 order by 字段名 asc //升序
select * from 表名 order by 字段名 desc //降序
标签:ZSET,数据类型,top5,Redis,用户,score,key,点赞,id From: https://blog.51cto.com/AmbitionGarden/8114977