1. 程式人生 > 其它 >基於Redis實現點贊熱門榜單的功能

基於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;
    }
}