@Component
public class PraiseService {
@Autowired
StringRedisTemplate stringRedisTemplate;
/**
* 点赞
* @param blogId 点赞博客的id
* @param userId 当前用户id
*/
public void praise(Long blogId, Long userId) {
String key = "blog:like:" + blogId;
Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
if (null == score) {
//分数为时间戳,就可以根据时间,获取前几个点赞的userI
stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
} else {
//如果已点赞,则取消
stringRedisTemplate.opsForZSet().remove(key, userId.toString());
}
}
/**
* 获取点赞前几名
* @param blogId 点赞博客的id
* @param top 前几名
* @return
*/
public Set<User> praiseUserSet(Long blogId, int top) {
String key = "blog:like:" + blogId;
Set<String> tops = stringRedisTemplate.opsForZSet().range(key, 0, top - 1);
if (CollectionUtil.isEmpty(tops)){
return null;
}
List<Long> ids = tops.stream().map(Long::valueOf).collect(Collectors.toList());
//存在一个问题,ids的顺序虽然符合需求的,但是数据库查询时in(...)时,就会乱,则
//sql 改为: select * from user where id (5,1) order by FIELD(id , 5,1)
//模拟数据库根绝userId 集合查询User对象
Set<User> userSet = new HashSet<>();
return userSet;
}
}