这里的场景是,自媒体文章发布以后,上下架情况会通过kafka传递给问文章模块,文章模块再更改对应文章的状态
自媒体文章端
@Resource
private KafkaTemplate kafkaTemplate;
/**
* 文章的上下架
* @param dto
* @return
*/
@Override
public ResponseResult downOrUp(WmNewsDto dto) {
//1.检查参数
if (dto!=null){
//2.查询文章
WmNews wmNews = getById(dto.getId());
//3.判断文章是否已发布
if (wmNews!=null&&wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
//4.修改文章enable
if (dto.getEnable()!=null&&dto.getEnable()>-1&&dto.getEnable()<2){
update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable,dto.getEnable()).eq(WmNews::getId,dto.getId()));
}
if (wmNews.getArticleId()!=null){
Map<String, Object> map = new HashMap<>();
map.put("articleId",wmNews.getArticleId());
map.put("enable",dto.getEnable());
kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
}
}
}
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
文章端
//先在文章单独创建一个包,创建一个监听器类
@Component
@Slf4j
public class ArtilceIsDownListener {
@Resource
private ApArticleConfigService apArticleConfigService;
@KafkaListener(topics = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC)
public void onMessage(String message){
if (StringUtils.isNotBlank(message)){
Map map = JSON.parseObject(message, Map.class);
apArticleConfigService.updateByMap(map);
log.info("article端文章配置修改,articleId={}",map.get("articleId"));
}
}
}
=====================================
//实现apArticleConfigService接口,并实现功能
@Service
@Slf4j
public class ApArticleConfigServiceImpl extends ServiceImpl<ApArticleConfigMapper,ApArticleConfig> implements ApArticleConfigService {
/**
* 修改文章配置
* @param map
*/
@Override
public void updateByMap(Map map) {
//0 下架 1 上架
Object enable = map.get("enable");
boolean isDown=true;
if (enable.equals(1)){
isDown=false;
}
//修改文章配置
update(Wrappers.<ApArticleConfig>lambdaUpdate().eq(ApArticleConfig::getArticleId,map.get("articleId")).set(ApArticleConfig::getIsDown,isDown));
}
}
=================================================
补充一点,kafka的安装
第一步,安装zookeeper
docker run -d --restart=always -e ALLOW_ANONYMOUS_LOGIN=yes --log-driver json-file --log-opt max-size=100m --log-opt max-file=2 --name zookeeper -p 2181:2181 -v /etc/localtime:/etc/localtime bitnami/zookeeper:latest
第二步,安装kafka
docker run -d --log-driver json-file --log-opt max-size=100m --log-opt max-file=2 --name kafka -p 9092:9092 -e KAFKA_BROKER_ID=0 -e KAFKA_ZOOKEEPER_CONNECT=192.168.200.130:2181/kafka -e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://192.168.200.130:9092 -e KAFKA_LISTENERS=PLAINTEXT://0.0.0.0:9092 -v /etc/localtime:/etc/localtime bitnami/kafka:latest
镜像会自动下载,一键三连哟,每天更新