需要星星支持 谢谢 ~
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集合的原因是需要对文章热度数据进行排序。
下面是程序启动打印的日志记录: