JavaWeb_LeadNews_Day10-Xxljob, Redis实现定时热文章

JavaWeb_LeadNews_Day10-Xxljob, Redis实现定时热文章

  • xxl-job概述
    • windows部署调度中心
    • docker部署调度中心
  • xxl-job入门案例
  • xxl-job分片广播
  • 热点文章定时计算
    • 思路分析
    • 具体实现
      • 热文章计算
      • 定时计算
  • 查询文章接口改造
  • 来源
  • Gitee

xxl-job概述

windows部署调度中心

  1. 运行 xxl-job\doc\db\tables_xxl_job.sql
  2. 修改 xxl-job-admin子模块下的application.properties
    spring.datasource.password=1234
    
  3. 启动 xxl-job-admin子模块下的启动程序
  4. 访问localhost:8080/xxl-job-admin, 账号: admin, 密码:123456

docker部署调度中心

  1. 创建mysql容器
docker run -p 3306:3306 --name mysql57 \
-v /opt/mysql/conf:/etc/mysql \
-v /opt/mysql/logs:/var/log/mysql \
-v /opt/mysql/data:/var/lib/mysql \
-e MYSQL_ROOT_PASSWORD=root \
-d mysql:5.7.25
  1. 拉取镜像
docker pull xuxueli/xxl-job-admin:2.3.0
  1. 创建xxl-job-admin容器
docker run -e PARAMS="--spring.datasource.url=jdbc:mysql://192.168.174.133:3306/xxl_job?Unicode=true&characterEncoding=UTF-8 \
--spring.datasource.username=root \
--spring.datasource.password=root" \
-p 8888:8080 -v /tmp:/data/applogs \
--name xxl-job-admin -d xuxueli/xxl-job-admin:2.3.0

xxl-job入门案例

  1. 调度中心新建示例任务
  2. 依赖
    <dependency>
        <groupId>com.xuxueli</groupId>
        <artifactId>xxl-job-core</artifactId>
        <version>2.3.0</version>
    </dependency>
    
  3. 配置
    application.yml
    server:
      port: 8881
    
    xxl:
      job:
        admin:
          addresses: http://192.168.174.133:8888/xxl-job-admin
        executor:
          appname: xxl-job-executor-sample
          port: 9999
    
    XxlJobConfig.java
    java">@Configuration
    public class XxlJobConfig {
        private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);
    
        @Value("${xxl.job.admin.addresses}")
        private String adminAddresses;
    
        @Value("${xxl.job.executor.appname}")
        private String appname;
    
        @Value("${xxl.job.executor.port}")
        private int port;
    
        @Bean
        public XxlJobSpringExecutor xxlJobExecutor() {
            logger.info(">>>>>>>>>>> xxl-job config init.");
            XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
            xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
            xxlJobSpringExecutor.setAppname(appname);
            xxlJobSpringExecutor.setPort(port);
    
            return xxlJobSpringExecutor;
        }
    
        /**
         * 针对多网卡、容器内部署等情况,可借助 "spring-cloud-commons" 提供的 "InetUtils" 组件灵活定制注册IP;
         *
         *      1、引入依赖:
         *          <dependency>
         *             <groupId>org.springframework.cloud</groupId>
         *             <artifactId>spring-cloud-commons</artifactId>
         *             <version>${version}</version>
         *         </dependency>
         *
         *      2、配置文件,或者容器启动变量
         *          spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.'
         *
         *      3、获取IP
         *          String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
         */
    }
    
  4. 任务代码
    java">@Component
    public class HelloJob {
    
        @XxlJob("demoJobHandler")
        public void demoJobHandler()
        {
            XxlJobHelper.log("XXL-JOB, Hello World.");
            System.out.println("简单任务执行...");
        }
    
    }
    

xxl-job分片广播

  1. 创建分片执行器 xxl-job-sharding-sample
  2. 创建任务, 路由策略为分片广播
  3. 分片广播任务代码, 创建多个实例
    java">@XxlJob("shardingJobHandler")
    public void shardingJobHandler()
    {
        // 分片的参数
        int shardIndex = XxlJobHelper.getShardIndex(); // 实例在集群中的序号
        int shardTotal = XxlJobHelper.getShardTotal(); // 集群总量
    
        // 业务逻辑
        List<Integer> list = getList();
        for (Integer integer : list) {
            if(integer % shardTotal == shardIndex){
                System.out.println("当前分片: "+shardIndex+", 当前任务项: "+integer);
            }
        }
    }
    
    public List<Integer> getList()
    {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            list.add(i);
        }
        return list;
    }
    

热点文章定时计算

思路分析

具体实现

热文章计算

java">@Slf4j
@Service
@Transactional
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 计算热门文章
     */
    @Override
    public void computeHotArticle() {
        // 1. 查询前5天的文章数据
        Date dayParam = DateTime.now().minusDays(5).toDate();
        List<ApArticle> articleList = apArticleMapper.findArticleListByLast5days(dayParam);

        // 2. 计算文章的分值
        List<HotArticleVo> hotArticleVoList = getHotArticleVoList(articleList);

        // 3. 为每个频道缓存30条分值较高的文章
        cacheTagToRedis(hotArticleVoList);
    }

    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private CacheService cacheService;


    /**
     * 为每个频道缓存30条分值较高的文章
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        // 为每个频道缓存30条分值较高的文章
        ResponseResult responseResult = wemediaClient.getChannels();
        if(responseResult.getCode().equals(200)){
            String jsonString = JSON.toJSONString(responseResult.getData());
            List<WmChannel> wmChannelList = JSON.parseArray(jsonString, WmChannel.class);
            // 检索出每个频道的文章
            if(wmChannelList!=null){
                for (WmChannel wmChannel : wmChannelList) {
                    List<HotArticleVo> hotArticleVos = hotArticleVoList.stream().filter(item ->
                        item.getChannelId().equals(wmChannel.getId())
                    ).collect(Collectors.toList());

                    // 给文章排序, 取30条分值较高的文章存入redis key: 频道id value: 30条分值较高的文章
                    sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId());
                }
            }
        }

        // 设置推荐数据
        // 给文章排序, 取30条分值较高的文章存入redis key: 频道id value: 30条分值较高的文章
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 排序并且缓存数据
     * @param hotArticleVos
     * @param key
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        hotArticleVos = hotArticleVos.stream().sorted(
                Comparator.comparing(HotArticleVo::getScore).reversed()
        ).collect(Collectors.toList());
        if(hotArticleVos.size() > 30){
            hotArticleVos = hotArticleVos.subList(0, 30);
        }
        cacheService.set(key, JSON.toJSONString(hotArticleVos));
    }


    /**
     * 获取热文章列表
     * @param articleList
     * @return
     */
    private List<HotArticleVo> getHotArticleVoList(List<ApArticle> articleList) {
        List<HotArticleVo> articleVoList = new ArrayList<>();
        if(articleList!=null) {
            for (ApArticle apArticle : articleList) {
                HotArticleVo hotArticleVo = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, hotArticleVo);
                Integer score = computeArticleScore(apArticle);
                hotArticleVo.setScore(score);
                articleVoList.add(hotArticleVo);
            }
        }
        return articleVoList;
    }

    /**
     * 计算文章分数
     * @param apArticle
     * @return
     */
    private Integer computeArticleScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT*apArticle.getLikes();
        }
        if(apArticle.getComment() != null){
            score += ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT*apArticle.getComment();
        }
        if(apArticle.getCollection() != null){
            score += ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT*apArticle.getCollection();
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        return score;
    }
}

// ApArticleMapper.java
List<ApArticle> findArticleListByLast5days(@Param("dayParam") Date dayParam);

// ApArticleMapper.xml
<select id="findArticleListByLast5days" resultType="com.heima.model.article.pojos.ApArticle">
    SELECT
    aa.*
    FROM
    `ap_article` aa
    LEFT JOIN ap_article_config aac ON aa.id = aac.article_id
    <where>
        and aac.is_delete != 1
        and aac.is_down != 1
        <if test="dayParam != null">
            and aa.publish_time <![CDATA[>=]]> #{dayParam}
        </if>
    </where>
</select>

总结:

  1. ApArticleMapper.java中的形参必须添加@Param注解, 否则在ApArticleMapper.xml中会将dayParam解释为Date的属性然后报错.

定时计算

  1. 新建热文章计算执行器leadnews-hot-article-executor
  2. 新建定时任务
  3. 依赖和配置
  4. 任务代码
    java">@Component
    @Slf4j
    public class ComputeHotArticleJob {
    
        @Autowired
        private HotArticleService hotArticleService;
    
        @XxlJob("computeHotArticleJob")
        public void handle()
        {
            log.info("热文章分值计算调度任务开始执行...");
            hotArticleService.computeHotArticle();
            log.info("热文章分值计算调度任务执行结束...");
        }
    
    }
    

查询文章接口改造

java">// article-Controller
public class ArticleHomeController {

    ...

    public ResponseResult load(@RequestBody ArticleHomeDto articleHomeDto)
    {
        // return apArticleService.load(articleHomeDto, ArticleConstants.LOADTYPE_LOAD_MORE);
        return apArticleService.load2(articleHomeDto, ArticleConstants.LOADTYPE_LOAD_MORE, true);
    }

    ...
}

// article-Service
public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {
    if(firstPage==true){
        String jsonString = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
        if(StringUtils.isNotBlank(jsonString)){
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonString, HotArticleVo.class);
            return ResponseResult.okResult(hotArticleVoList);
        }
    }
    return load(dto, type);
}

来源

黑马程序员. 黑马头条

Gitee

https://gitee.com/yu-ba-ba-ba/leadnews


http://www.niftyadmin.cn/n/4994633.html

相关文章

Python-图像拼接神器-stitching

多幅图像的拼接 采用这个包&#xff0c;图像拼接结果很好~ 代码只需要三四行 import stitching import cv2imgs ["data/test02/1Hill.jpg","data/test02/2Hill.jpg","data/test02/3Hill.jpg",] stitcher stitching.Stitcher() panorma stit…

context.WithTimeout()之实现Gorm超时控制

文章目录 1. 写在前面2. 如何实现超时控制3. 实现Gorm的超时控制4. 看向更底层5. 实现超时控制逻辑6. Gorm内部的context done校验逻辑7. 小结8. 参考文档 1. 写在前面 Context是Golang中的上下文&#xff0c;Gorm是当前用的比较多的SQL组件库&#xff0c;在Gorm中&#xff0c…

【力扣周赛】第 359 场周赛(选择区间型DP⭐⭐⭐⭐⭐新题型 双指针)

文章目录 竞赛链接Q1&#xff1a;7004. 判别首字母缩略词&#xff08;模拟&#xff09;Q2&#xff1a;6450. k-avoiding 数组的最小总和解法1——贪心哈希表解法2——数学公式 Q3&#xff1a;7006. 销售利润最大化⭐⭐⭐线性DP相似题目列表2008. 出租车的最大盈利&#xff08;和…

论文阅读_扩散模型_DDPM

英文名称: Denoising Diffusion Probabilistic Models 中文名称: 去噪扩散概率模型 论文地址: http://arxiv.org/abs/2006.11239 代码地址1: https://github.com/hojonathanho/diffusion &#xff08;论文对应代码 tensorflow&#xff09; 代码地址2: https://github.com/AUTOM…

逆向工程-架构真题(二十)

结构化程序设计采用自顶向下、逐步求精及模块化程序设计方法&#xff0c;通过&#xff08;&#xff09;三种基本控制结构可以构造出任何单入口单出口程序。 顺序、选择和嵌套顺序、分支和循环分支、并发和循环跳转、选择和并发 答案&#xff1a;B 解析&#xff1a; 结构化设…

十一、MySQL(DQL)聚合函数

1、聚合函数 注意&#xff1a;在使用聚合函数时&#xff0c;所有的NULL是不参与运算的。 2、实际操作&#xff1a; &#xff08;1&#xff09;初始化表格 &#xff08;2&#xff09;统计该列数据的个数 基础语法&#xff1a; select count(字段名) from 表名; &#xff1b;统…

并发-线程

使用线程 进程里可以创建多个线程&#xff0c;线程都有各自的计数器、堆栈和局部变量等属性&#xff0c;并能访问共享内存变量。 使用多线程 更多的处理器核心更快的响应时间更好的编程模型 线程优先级 操作系统基本采用时分的形式调度运行的线程&#xff0c;线程分配到若干…

ABP中的ConcurrencyStamp的自动化管理

在ABP中&#xff0c;你可以使得Entity直接继承接口 IHasConcurrencyStamp 然后再EF中的XXXDbContextModelCreatingExtensions中的ConfigureByConvention会看到如下代码 public static void TryConfigureConcurrencyStamp(this EntityTypeBuilder b){if (b.Metadata.ClrType.Is…