Redis -- 达人探店--朋友圈点赞

本文介绍了如何使用Spring Boot和Redis实现一个博客点赞功能,包括点赞操作的原子性和排行榜的实时更新。通过StringRedisTemplate操作有序集合,实现实时点赞数和用户排名的维护。
摘要由CSDN通过智能技术生成

 

@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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值