xxlJob定时任务,文章的上下架

第八章 分布式任务调度&人工审核

目标

  • 能够理解什么是分布式任务调度
  • 能够掌握xxl-job的基本使用
  • 能够使用xxl-job解决黑马头条项目中定时任务的功能
  • 能够完成自媒体文章人工审核功能
  • 能够完成自媒体端文章上下架同步的问题

1 分布式任务调度

详细查看资料文件夹中的xxl-job相关文档。

2 自媒体文章审核-定时任务扫描待发布文章

2.1 需求分析

  • 前期回顾:在自媒体文章审核的时候,审核通过后,判断了文章的发布时间大于当前时间,这个时候并没有真正的发布文章,而是把文章的状态设置为了8(审核通过待发布)
  • 定时任务的作用就是每分钟去扫描这些待发布的文章,如果当前文章的状态为8,并且发布时间小于当前时间的,立刻发布当前文章

2.2 自媒体文章数据准备

自动审核的代码都是通过自媒体文章的id进行审核的,这个时候需要在admin端远程调用自媒体端查询文章状态为8且发布时间小于当前时间的文章id列表

(1)修改WmNewsControllerApi接口,新增方法

/**
     * 查询需要发布的文章id列表
     * @return
     */
List<Integer> findRelease();

(2)业务层

在自媒体微服务中的WmNewsService新增方法

/**
     * 查询需要发布的文章id列表
     * @return
     */
List<Integer> findRelease();

实现方法:

/**
     * 查询需要发布的文章id列表
     * @return
     */
@Override
public List<Integer> findRelease(){
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8).lt(WmNews::getPublishTime,new Date()));
        List<Integer> resultList = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return resultList;
    }

(3)控制器

WmNewsController中新增方法

@GetMapping("/findRelease")
@Override
public List<Integer> findRelease() {
    return wmNewsService.findRelease();
}

(4)在admin端添加远程调用feign接口

修改WemediaFeign接口添加方法

@GetMapping("/api/v1/news/findRelease")
List<Integer> findRelease();

2.3 xxl-job调度中心创建调度任务

(1)新建执行器,原则上一个项目一个执行器,方便管理

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pyohCSxf-1627036020488)(assets\1586018109877.png)]

(2)新建任务

如下图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6TTXnx59-1627036020490)(assets\1586018203056.png)]

执行器:选择自己新建的执行器

路由策略:轮询

Cron: * 1 * * * ?每分钟执行一次

2.4 xxl-job集成到项目中

(1)引入依赖信息

在leadnews-common中引入依赖

<dependency>
    <groupId>com.xuxueli</groupId>
    <artifactId>xxl-job-core</artifactId>
</dependency>

(2)在admin端的application.yml中加入以下配置:

xxljob:
  admin:
    addresses: http://localhost:8888/xxl-job-admin
  executor:
    appname: leadnews-admin-executor
    port: 9999

(3)创建配置类

package com.heima.admin.config;

import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Log4j2
@Configuration
public class XxlJobConfig {

    @Value("${xxljob.admin.addresses}")
    private String adminAddresses;

    @Value("${xxljob.executor.appname}")
    private String appName;

    @Value("${xxljob.executor.port}")
    private int port;

    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {
        log.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
        xxlJobSpringExecutor.setAppName(appName);
        xxlJobSpringExecutor.setPort(port);
        xxlJobSpringExecutor.setLogRetentionDays(30);

        return xxlJobSpringExecutor;
    }
}

3 人工审核文章

2.5 创建调度任务,定时审核

创建任务,查询自媒体文章后进行审核

package com.heima.admin.job;

import com.heima.admin.feign.WemediaFeign;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Log4j2
public class WeMediaNewsAutoScanJob {

    @Autowired
    private WemediaNewsAutoScanService wemediaNewsAutoScanService;

    @Autowired
    private WemediaFeign wemediaFeign;

    /**
     * 每天0点执行一次
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("wemediaAutoScanJob")
    public ReturnT<String> hello(String param) throws Exception {
        log.info("自媒体文章审核调度任务开始执行....");
        List<Integer> releaseIdList = wemediaFeign.findRelease();
        if(null!=releaseIdList && !releaseIdList.isEmpty()){
            for (Integer id : releaseIdList) {
                wemediaNewsAutoScanService.autoScanByMediaNewsId(id);
            }
        }
        log.info("自媒体文章审核调度任务执行结束....");
        return ReturnT.SUCCESS;
    }

}

2.6 测试

在数据库中准备好数据,数据状态为8且发布时间小于当前时间

3 admin端-人工审核文章

3.1 需求分析

自媒体文章如果没有自动审核成功,而是到了人工审核(自媒体文章状态为3),需要在admin端人工处理文章的审核

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-03w6c9oQ-1627036020493)(assets\1599323042719.png)]

平台管理员可以查看待人工审核的文章信息,可以通过(状态改为4)驳回(状态改为2)

也可以通过点击查看按钮,查看文章详细信息,查看详情后可以根据内容判断是否需要通过审核

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-y9STsbln-1627036020496)(assets\1599323199916.png)]

3.2 自媒体端实现

(1)自媒体端-接口定义

1 需要分页查询自媒体文章信息,可以根据标题模糊查询

2 需要根据文章id查看文章的详情

3 修改文章的状态,已实现

修改WmNewsControllerApi接口,添加如下方法

/**
     * 查询文章列表
     * @param dto
     * @return
     */
public PageResponseResult findList(NewsAuthDto dto);

/**
     * 查询文章详情
     * @param id
     * @return
     */
public WmNewsVo findWmNewsVo(Integer id) ;

NewsAuthDto

package com.heima.model.admin.dtos;

import com.heima.model.common.dtos.PageRequestDto;
import lombok.Data;

@Data
public class NewsAuthDto extends PageRequestDto {

    /**
     * 文章标题
     */
    private String title;
}

从原型图中可以看出,返回的文章信心中包含了作者信息,但是作者名称并不能在文章表中体现,只有一个用户id,目前需要通过用户id关联查询用户表或许完整数据

vo:value object 值对象 / view object 表现层对象,主要对应页面显示(web页面)的数据对象

需要先封装一个vo类,来存储文章信息和作者名称

package com.heima.model.wemedia.vo;

import com.heima.model.wemedia.pojos.WmNews;
import lombok.Data;

@Data
public class WmNewsVo  extends WmNews {
    /**
     * 作者名称
     */
    private String authorName;
}

(2)自媒体端-mapper定义

通过刚才分析,不管是查看文章列表或者是查询文章详情,都需要返回带作者的文章信息,需要关联查询获取数据,而mybatis-plus暂时不支持多表查询,需要手动定义mapper文件实现

修改WmNewsMapper接口添加两个方法

@Mapper
public interface WmNewsMapper extends BaseMapper<WmNews> {
    List<WmNewsVo> findListAndPage(@Param("dto") NewsAuthDto dto);
    int findListCount(@Param("dto") NewsAuthDto dto);
}

在src\main\resources\mapper目录下新建WmNewsMapper.xml文件

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.heima.wemedia.mapper.WmNewsMapper">    <select id="findListAndPage" resultType="com.heima.model.wemedia.vo.WmNewsVo" parameterType="com.heima.model.admin.dtos.NewsAuthDto">        SELECT            wn.*, wu.`name` authorName        FROM            wm_news wn        LEFT JOIN wm_user wu ON wn.user_id = wu.id        <where>            <if test="dto.title != null and dto.title != ''">                and wn.title like #{dto.title}            </if>        </where>        LIMIT #{dto.page},#{dto.size}    </select>    <select id="findListCount" resultType="int" parameterType="com.heima.model.admin.dtos.NewsAuthDto">        SELECT            count(1)        FROM            wm_news wn        LEFT JOIN wm_user wu ON wn.user_id = wu.id        <where>            <if test="dto.title != null and dto.title != ''">                and wn.title like #{dto.title}            </if>        </where>    </select></mapper>

(3)自媒体端-业务层

修改WmNewsService接口,新增以下方法

/**     * 分页查询文章信息     * @param dto     * @return     */public PageResponseResult findListAndPage(NewsAuthDto dto);/**     * 查询文章详情     * @param id     * @return     */WmNewsVo findWmNewsVo(Integer id);

实现类方法:

@Autowiredprivate WmNewsMapper wmNewsMapper;public PageResponseResult findListAndPage(NewsAuthDto dto){    //1.检查参数    dto.checkParam();    //设置起始页    dto.setPage((dto.getPage()-1)*dto.getSize());    if(StringUtils.isNotBlank(dto.getTitle())) {       dto.setTitle("%" + dto.getTitle() + "%");     }    //2.分页查询    List<WmNewsVo> list = wmNewsMapper.findListAndPage(dto);    //统计多少条数据    int count = wmNewsMapper.findListCount(dto);        //3.结果返回    PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),count);    responseResult.setData(list);    return responseResult;}@Autowiredprivate WmUserMapper wmUserMapper;@Overridepublic WmNewsVo findWmNewsVo(Integer id) {    //1.查询文章信息    WmNews wmNews = getById(id);    //2.查询作者    WmUser wmUser = null;    if(wmNews!=null && wmNews.getUserId() != null){        wmUser = wmUserMapper.selectById(wmNews.getUserId());    }    //3.封装vo信息返回    WmNewsVo wmNewsVo = new WmNewsVo();    BeanUtils.copyProperties(wmNews,wmNewsVo);    if(wmUser != null){        wmNewsVo.setAuthorName(wmUser.getName());    }    return wmNewsVo;}

(4)自媒体端-控制层

修改WmNewsController类,添加以下方法

@PostMapping("/findList")@Overridepublic PageResponseResult findList(@RequestBody NewsAuthDto dto){    return wmNewsService.findListAndPage(dto);}@GetMapping("/find_news_vo/{id}")@Overridepublic WmNewsVo findWmNewsVo(@PathVariable("id") Integer id) {    return wmNewsService.findWmNewsVo(id);}

3.3 admin端实现

(1)admin端-api接口定义

1 需要分页查询自媒体文章信息,可以根据标题模糊查询

2 当审核通过后,修改文章状态为4

3 当审核驳回后,修改文章状态为3,并且需要说明原因

4 需要根据文章id查看文章的详情

package com.heima.apis.admin;import com.heima.model.admin.dtos.NewsAuthDto;import com.heima.model.common.dtos.ResponseResult;public interface NewsAuthControllerApi {    /**     * 查询自媒体文章列表     * @param dto     * @return     */    public ResponseResult findNews(NewsAuthDto dto);    /**     * 查询文章详情     * @param id     * @return     */    public ResponseResult findOne(Integer id);    /**     * 文章审核成功     * @param dto     * @return     */    public ResponseResult authPass(NewsAuthDto dto);    /**     * 文章审核失败     * @param dto     * @return     */    public ResponseResult authFail(NewsAuthDto dto);}

在NewsAuthDto补充两个属性id和msg

package com.heima.model.admin.dtos;import com.heima.model.common.dtos.PageRequestDto;import lombok.Data;@Datapublic class NewsAuthDto extends PageRequestDto {    /**     * 文章标题     */    private String title;    private Integer id;        /**     * 失败原因     */    private String msg;}

(2)admin端-mapper定义

(3)admin端-远程调用接口

在admin端远程接口WemediaFeign中新增如下方法

查看文章列表和查询文章详情,其中审核成功或失败可以调用之前定义好的修改方法updateWmNews()

在查询列表的方法需要通过远程接口进行分页查看,返回值是PageResponseResult对象

@PostMapping("/api/v1/news/findList/")public PageResponseResult findList(NewsAuthDto dto);@GetMapping("/api/v1/news/find_news_vo/{id}")public WmNewsVo findWmNewsVo(@PathVariable("id") Integer id);

(4)admin端-业务层

修改WemediaNewsAutoScanService业务层接口,新增以下方法

/**     * 根据文章标题分页查询自媒体文章列表     * @param dto     * @return     */public PageResponseResult findNews(NewsAuthDto dto);/**     * 根据文章id文章信息     * @param id     * @return     */public ResponseResult findOne(Integer id);/**     * 审核通过或驳回     * @param type  0 为驳回  1位通过     * @param dto     * @return     */public ResponseResult updateStatus(Integer type,NewsAuthDto dto);

实现类方法:

@Overridepublic PageResponseResult findNews(NewsAuthDto dto) {    //分页查询    PageResponseResult responseResult =  wemediaFeign.findList(dto);    //有图片需要显示,需要fasfdfs服务器地址    responseResult.setHost(fileServerUrl);    return responseResult;}@Overridepublic ResponseResult findOne(Integer id) {    //1参数检查    if(id == null){        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);    }    //2查询数据    WmNewsVo wmNewsVo = wemediaFeign.findWmNewsVo(id);    //结构封装    ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);    responseResult.setHost(fileServerUrl);    return responseResult;}@Overridepublic ResponseResult updateStatus(Integer type, NewsAuthDto dto) {    //1.参数检查    if(dto == null || dto.getId() == null){        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);    }    //2.查询文章    WmNews wmNews = wemediaFeign.findById(dto.getId());    if(wmNews == null){        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);    }    //3.审核没有通过    if(type.equals(0)){        updateWmNews(wmNews,(short)2,dto.getMsg());    }else if(type.equals(1)){        //4.人工审核通过        updateWmNews(wmNews,(short)4,"人工审核通过");    }    return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);}

(5)admin端-控制层

package com.heima.admin.controller.v1;import com.heima.admin.service.WemediaNewsAutoScanService;import com.heima.apis.admin.NewsAuthControllerApi;import com.heima.model.admin.dtos.NewsAuthDto;import com.heima.model.common.dtos.ResponseResult;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.annotation.Order;import org.springframework.web.bind.annotation.*;@RestController@RequestMapping("/api/v1/news_auth")public class NewsAuthController implements NewsAuthControllerApi {    @Autowired    private WemediaNewsAutoScanService wemediaNewsAutoScanService;    @PostMapping("/list")    @Override    public ResponseResult findNews(@RequestBody NewsAuthDto dto){        return wemediaNewsAutoScanService.findNews(dto);    }    @GetMapping("/one/{id}")    @Override    public ResponseResult findOne(@PathVariable("id") Integer id){        return wemediaNewsAutoScanService.findOne(id);    }    @PostMapping("/auth_pass")    @Override    public ResponseResult authPass(@RequestBody NewsAuthDto dto){        return wemediaNewsAutoScanService.updateStatus(1,dto);    }    @PostMapping("/auth_fail")    @Override    public ResponseResult authFail(@RequestBody NewsAuthDto dto){        return wemediaNewsAutoScanService.updateStatus(0,dto);    }}

3.4 测试

可打开页面直接测试

4 自媒体端-文章上下架

4.1 思路分析

在自媒体文章管理中有文章上下架的操作,上下架是文章已经审核通过发布之后的文章,目前自动审核文章和人工审核文章都已完成,可以把之前代码补充,使用异步的方式,修改app端文章的配置信息即可。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wFIrdiUN-1627036020497)(assets\1599398923029.png)]

4.2 自媒体文章发消息通知下架

修改WmNewsServiceImpl中的downOrUp方法,发送消息

@Overridepublic ResponseResult downOrUp(WmNewsDto dto) {    //1.检查参数    if(dto == null || dto.getId() == null){        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);    }    //2.查询文章    WmNews wmNews = getById(dto.getId());    if(wmNews == null){        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");    }    //3.判断文章是否发布    if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态,不能上下架");    }    //4.修改文章状态,同步到app端(后期做)TODO    if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){        if(wmNews.getArticleId()!=null){            Map<String,Object> mesMap = new HashMap<>();            mesMap.put("enable",dto.getEnable());            mesMap.put("articleId",wmNews.getArticleId());            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(mesMap));        }        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));    }    return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);}

常量类中定义topic

package com.heima.common.constants.message;public class WmNewsMessageConstants {    public static final String WM_NEWS_UP_OR_DOWN_TOPIC="wm.news.up.or.down.topic";}

4.3 文章微服务

文章微服务需要接收消息

在application.yml文件中添加kafka消费者的配置

kafka:    bootstrap-servers: 192.168.200.130:9092    consumer:      group-id: ${spring.application.name}-kafka-group      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer

编写listener,如下:

package com.heima.article.kafka.listener;import com.alibaba.fastjson.JSON;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.heima.article.service.ApArticleConfigService;import com.heima.common.constants.message.NewsAutoScanConstants;import com.heima.common.constants.message.WmNewsMessageConstants;import com.heima.model.article.pojos.ApArticleConfig;import org.apache.kafka.clients.consumer.ConsumerRecord;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.kafka.annotation.KafkaListener;import org.springframework.stereotype.Component;import java.util.Map;import java.util.Optional;@Componentpublic class ArticleIsDownListener {    @Autowired    private ApArticleConfigService apArticleConfigService;    @KafkaListener(topics = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC)    public void receiveMessage(ConsumerRecord<?,?> record){        Optional<? extends ConsumerRecord<?, ?>> optional = Optional.ofNullable(record);        if(optional.isPresent()){            String value = (String) record.value();            Map map = JSON.parseObject(value, Map.class);            apArticleConfigService.update(Wrappers.<ApArticleConfig>lambdaUpdate()            .eq(ApArticleConfig::getArticleId,map.get("articleId")).set(ApArticleConfig::getIsDown,map.get("enable")));        }    }}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值