Loading

基于Redis实现点赞热门榜单的功能

基于Redis实现点赞+热门榜单的功能

package com.wanda.spiderman;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashSet;
import java.util.Set;

/**
 * @author 知非
 * @date 2021/11/10 19:38
 */
public class StarDemo {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 记录点赞数的 key
     */
    private String starKey = "star";
    /**
     * 记录热榜帖子 ID 的 key
     */
    private String hotKey = "hot";
    /**
     * 阈值
     */
    private Long threshold = 50L;

    public StarDemo() {
    }

    public StarDemo(StringRedisTemplate redisTemplate, String starKey, String hotKey, Long threshold) {
        this.redisTemplate = redisTemplate;
        this.starKey = starKey;
        this.hotKey = hotKey;
        this.threshold = threshold;
    }

    /**
     * 点赞
     *
     * @param id 帖子ID
     */
    public void star(String id) {
        // 判断是否已经缓存帖子ID
        if (redisTemplate.opsForHash().hasKey(starKey, id)) {
            // 对帖子点赞数进行自增
            Long number = redisTemplate.opsForHash().increment(starKey, id, 1);
            // 判断点赞数是否以及超过热门
            if (number >= threshold) {
                addHotList(id, number);
            }
        } else {
            redisTemplate.opsForHash().put(starKey, id, 0);
        }
    }

    /**
     * 添加到热门榜单
     *
     * @param id     帖子ID
     * @param number 点赞数
     */
    private void addHotList(String id, Long number) {
        // 添加到热门队列
        System.out.println("榜单排名:" + redisTemplate.opsForZSet().rank(hotKey, id));
        if (redisTemplate.opsForZSet().rank(hotKey, id) == null) {
            System.out.println("热门榜单点赞数:" + id);
        } else {
            System.out.println("超过阈值,添加到热门榜单:" + id);
        }
        redisTemplate.opsForZSet().add(hotKey, id, number);
    }

    /**
     * 获取热门榜单
     *
     * @param start 起始
     * @param end   结束
     * @return 热门榜单
     */
    private Set<String> getHotList(Long start, Long end) {
        Set<String> hotList = redisTemplate.opsForZSet().range(hotKey, start, end);
        if (hotList == null) {
            return new HashSet<>();
        }
        return hotList;
    }
}
posted @ 2021-11-10 22:15  WanDa92632  阅读(148)  评论(0)    收藏  举报