浪海博客 文字排行榜预热功能

本文介绍了如何在SpringBoot应用启动时,通过实现CommandLineRunner接口的ArticleCommandRunner类,预加载文章热度排行榜数据,确保系统启动时不为空。涉及到了获取公开文章、计算热度值以及使用Redis存储排序数据的过程。
摘要由CSDN通过智能技术生成

需要星星支持 谢谢 ~ 

gitee地址:https://gitee.com/langhai666/langhai-blog

github地址:https://github.com/Allenkuzma/langhaiblogs

以下完整代码请查看开源项目 浪海博客,主要关注下面一个类。

cc.langhai.config.runner.ArticleCommandRunner

package cc.langhai.config.runner;

import cc.langhai.config.constant.ArticleConstant;
import cc.langhai.domain.Article;
import cc.langhai.service.ArticleService;
import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.TreeSet;

/**
 * 热点排名前十的文章预热
 *
 * @author langhai
 * @date 2023-03-19 18:38
 */
@Slf4j
@Component
public class ArticleCommandRunner implements CommandLineRunner {

    @Autowired
    private ArticleService articleService;

    @Override
    public void run(String... args) throws Exception {
        // 获取10篇公开文章
        PageInfo<Article> pageInfo = articleService.search(1, 10, null, null);
        List<Article> articleHeat = articleService.getArticleHeat(pageInfo.getList());
        TreeSet<Article> articleHeatTop10 = ArticleConstant.ARTICLE_HEAT_TOP_10;
        if(CollectionUtil.isNotEmpty(articleHeat)){
            articleHeatTop10.addAll(articleHeat);
            log.info("10篇文章成功预热");
        }
    }
}

在系统启动时候,有时候我们会对数据进行预热加载,例如 浪海博客 系统在启动的时候有一个文章热度前十排行榜的功能,为了避免系统刚启动的时候,这一块的数据是空白的,所以需要对文章数据进行加载。

在springboot项目工程中,实现org.springframework.boot.CommandLineRunner这个接口,重写run方法即可实现预加载功能。

这里获取文章的逻辑是,首先获取十篇公开的文章,然后获取这十篇文章的热度值,这个值存储在redis里面。

    /**
     * 热点排名前十的文章
     */
    public static TreeSet<Article> ARTICLE_HEAT_TOP_10 = new TreeSet<>();

存储到这个TreeSet集合里面,这里使用TreeSet集合的原因是需要对文章热度数据进行排序。

下面是程序启动打印的日志记录:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值