fix: 批量发布改为事务提交后再异步,避免草稿永久卡在发布中

This commit is contained in:
2026-10-16 15:24:08 +08:00
parent 5dee928321
commit 4c3b2870a4
28 changed files with 198 additions and 847 deletions
@@ -1,11 +1,19 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.publishdesk.service;
import org.springframework.security.core.Authentication;
/**
* 异步执行批量发布任务(避免同类自调用导致 @Async 失效)。
* <p>
* 调用方须在事务提交后再触发,并把请求线程的 Authentication 传入,
* 否则异步线程读不到未提交的 job,且 publish 会因无登录上下文失败。
*/
public interface PddGoodsPublishJobRunner {
void runJob(Long companyId, Long jobId);
void runJob(Long companyId, Long jobId, Authentication authentication);
void retryFailed(Long companyId, Long jobId);
void retryFailed(Long companyId, Long jobId, Authentication authentication);
/** 进程启动时回收中断的 RUNNING / 未启动 PENDING 任务(须在接口上声明,JDK 代理才能挂 @EventListener) */
void recoverInterruptedJobsOnReady();
}
@@ -8,8 +8,12 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
@@ -276,7 +280,10 @@ public class PddGoodsPublishDeskServiceImpl implements PddGoodsPublishDeskServic
throw new BusinessException("草稿「" + d.getTitle() + "」待校验(跨店克隆后请核对类目/运费)");
}
if (PddGoodsPublishDraftPO.STATUS_PUBLISHING.equals(d.getStatus())) {
throw new BusinessException("草稿「" + d.getTitle() + "」正在发布中");
releaseStalePublishLocks(companyId, d.getId());
if (hasActiveJobItem(companyId, d.getId())) {
throw new BusinessException("草稿「" + d.getTitle() + "」正在发布中");
}
}
if (!StringUtils.hasText(d.getPayloadJson()) || !d.getPayloadJson().contains("publishPayload")) {
throw new BusinessException("草稿「" + d.getTitle() + "」缺少可发布数据,请先在编辑器保存");
@@ -306,7 +313,8 @@ public class PddGoodsPublishDeskServiceImpl implements PddGoodsPublishDeskServic
draftMapper.updateById(d);
}
jobRunner.runJob(companyId, job.getId());
// 必须等事务提交后再异步,否则 runner 读不到 job 会静默退出,草稿永久卡在 PUBLISHING
scheduleJobAfterCommit(companyId, job.getId(), false);
return getJob(job.getId());
}
@@ -345,10 +353,81 @@ public class PddGoodsPublishDeskServiceImpl implements PddGoodsPublishDeskServic
job.setStatus(PddGoodsPublishJobPO.STATUS_PENDING);
job.setMessage("重试失败项中");
jobMapper.updateById(job);
jobRunner.retryFailed(companyId, jobId);
scheduleJobAfterCommit(companyId, jobId, true);
return getJob(jobId);
}
/**
* 事务提交后再启动异步任务,并传入当前登录态。
*/
private void scheduleJobAfterCommit(Long companyId, Long jobId, boolean retryFailed) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Runnable start = () -> {
if (retryFailed) {
jobRunner.retryFailed(companyId, jobId, authentication);
} else {
jobRunner.runJob(companyId, jobId, authentication);
}
};
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
start.run();
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
start.run();
}
});
}
/** 是否仍有进行中的投递明细(用于区分「真发布中」与上次异步丢失导致的假死) */
private boolean hasActiveJobItem(Long companyId, Long draftId) {
return jobItemMapper.selectCount(new LambdaQueryWrapper<PddGoodsPublishJobItemPO>()
.eq(PddGoodsPublishJobItemPO::getCompanyId, companyId)
.eq(PddGoodsPublishJobItemPO::getDraftId, draftId)
.in(PddGoodsPublishJobItemPO::getStatus,
PddGoodsPublishJobItemPO.STATUS_PENDING,
PddGoodsPublishJobItemPO.STATUS_RUNNING)) > 0;
}
/**
* 释放假死锁:事务未提交就异步退出时,job 永久 PENDING、明细永久 PENDING。
* 再次批量发布前把这类明细/任务作废,否则草稿会一直无法重投。
*/
private void releaseStalePublishLocks(Long companyId, Long draftId) {
List<PddGoodsPublishJobItemPO> items = jobItemMapper.selectList(
new LambdaQueryWrapper<PddGoodsPublishJobItemPO>()
.eq(PddGoodsPublishJobItemPO::getCompanyId, companyId)
.eq(PddGoodsPublishJobItemPO::getDraftId, draftId)
.in(PddGoodsPublishJobItemPO::getStatus,
PddGoodsPublishJobItemPO.STATUS_PENDING,
PddGoodsPublishJobItemPO.STATUS_RUNNING));
for (PddGoodsPublishJobItemPO item : items) {
PddGoodsPublishJobPO job = jobMapper.selectById(item.getJobId());
boolean stale = job == null
|| PddGoodsPublishJobPO.STATUS_SUCCESS.equals(job.getStatus())
|| PddGoodsPublishJobPO.STATUS_PARTIAL.equals(job.getStatus())
|| PddGoodsPublishJobPO.STATUS_FAILED.equals(job.getStatus())
|| (PddGoodsPublishJobPO.STATUS_PENDING.equals(job.getStatus())
&& job.getStartedAt() == null);
if (!stale) {
continue;
}
item.setStatus(PddGoodsPublishJobItemPO.STATUS_FAILED);
item.setErrorMessage("任务未执行或已中断,已自动释放");
jobItemMapper.updateById(item);
if (job != null && PddGoodsPublishJobPO.STATUS_PENDING.equals(job.getStatus())
&& job.getStartedAt() == null) {
job.setStatus(PddGoodsPublishJobPO.STATUS_FAILED);
job.setMessage("任务未启动已作废");
job.setFailCount(job.getTotalCount());
job.setFinishedAt(java.time.LocalDateTime.now());
jobMapper.updateById(job);
}
}
}
@Override
@Transactional
public PddGoodsPublishDraftVO pushPlatformDraft(Long id) {
@@ -6,7 +6,12 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddGoodsPublishDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddGoodsPublishResultVO;
@@ -38,21 +43,117 @@ public class PddGoodsPublishJobRunnerImpl implements PddGoodsPublishJobRunner {
private final PddGoodsPublishDraftShopStatService shopStatService;
private final ObjectMapper objectMapper;
/**
* 进程重启后:上一轮 @Async 已死,RUNNING/未启动 PENDING 任务与 PUBLISHING 草稿会永久卡住。
*/
@Override
@Async
public void runJob(Long companyId, Long jobId) {
process(companyId, jobId, false);
@EventListener(ApplicationReadyEvent.class)
public void recoverInterruptedJobsOnReady() {
LocalDateTime now = LocalDateTime.now();
// 从未 started 的 PENDING:典型是事务提交前异步已退出
List<PddGoodsPublishJobPO> orphanPending = jobMapper.selectList(
new LambdaQueryWrapper<PddGoodsPublishJobPO>()
.eq(PddGoodsPublishJobPO::getStatus, PddGoodsPublishJobPO.STATUS_PENDING)
.isNull(PddGoodsPublishJobPO::getStartedAt));
for (PddGoodsPublishJobPO job : orphanPending) {
failJobAndDrafts(job, now, "任务未启动已中断");
log.warn("publish desk job 从未启动,已作废 jobId={}", job.getId());
}
List<PddGoodsPublishJobPO> runningJobs = jobMapper.selectList(
new LambdaQueryWrapper<PddGoodsPublishJobPO>()
.eq(PddGoodsPublishJobPO::getStatus, PddGoodsPublishJobPO.STATUS_RUNNING));
for (PddGoodsPublishJobPO job : runningJobs) {
failJobAndDrafts(job, now, "服务重启,发布中断");
log.warn("publish desk job 从 RUNNING 恢复为 FAILED jobId={}", job.getId());
}
// 无进行中明细的 PUBLISHING 草稿(典型:异步在事务提交前退出)
List<PddGoodsPublishDraftPO> stuckDrafts = draftMapper.selectList(
new LambdaQueryWrapper<PddGoodsPublishDraftPO>()
.eq(PddGoodsPublishDraftPO::getStatus, PddGoodsPublishDraftPO.STATUS_PUBLISHING));
for (PddGoodsPublishDraftPO draft : stuckDrafts) {
long active = jobItemMapper.selectCount(new LambdaQueryWrapper<PddGoodsPublishJobItemPO>()
.eq(PddGoodsPublishJobItemPO::getDraftId, draft.getId())
.in(PddGoodsPublishJobItemPO::getStatus,
PddGoodsPublishJobItemPO.STATUS_PENDING,
PddGoodsPublishJobItemPO.STATUS_RUNNING));
if (active > 0) {
continue;
}
draft.setStatus(PddGoodsPublishDraftPO.STATUS_FAILED);
draft.setLastError("发布任务未执行或已中断,请重新发布");
draftMapper.updateById(draft);
log.warn("publish desk draft 从 PUBLISHING 恢复为 FAILED draftId={}", draft.getId());
}
}
@Override
@Async
public void retryFailed(Long companyId, Long jobId) {
process(companyId, jobId, true);
public void runJob(Long companyId, Long jobId, Authentication authentication) {
runWithAuth(authentication, () -> process(companyId, jobId, false));
}
@Override
@Async
public void retryFailed(Long companyId, Long jobId, Authentication authentication) {
runWithAuth(authentication, () -> process(companyId, jobId, true));
}
private void failJobAndDrafts(PddGoodsPublishJobPO job, LocalDateTime now, String reason) {
List<PddGoodsPublishJobItemPO> items = jobItemMapper.selectList(
new LambdaQueryWrapper<PddGoodsPublishJobItemPO>()
.eq(PddGoodsPublishJobItemPO::getJobId, job.getId())
.in(PddGoodsPublishJobItemPO::getStatus,
PddGoodsPublishJobItemPO.STATUS_PENDING,
PddGoodsPublishJobItemPO.STATUS_RUNNING));
for (PddGoodsPublishJobItemPO item : items) {
item.setStatus(PddGoodsPublishJobItemPO.STATUS_FAILED);
item.setErrorMessage(reason);
jobItemMapper.updateById(item);
PddGoodsPublishDraftPO draft = draftMapper.selectById(item.getDraftId());
if (draft != null
&& PddGoodsPublishDraftPO.STATUS_PUBLISHING.equals(draft.getStatus())) {
draft.setStatus(PddGoodsPublishDraftPO.STATUS_FAILED);
draft.setLastError(reason);
draftMapper.updateById(draft);
}
}
long ok = jobItemMapper.selectCount(new LambdaQueryWrapper<PddGoodsPublishJobItemPO>()
.eq(PddGoodsPublishJobItemPO::getJobId, job.getId())
.eq(PddGoodsPublishJobItemPO::getStatus, PddGoodsPublishJobItemPO.STATUS_SUCCESS));
long bad = jobItemMapper.selectCount(new LambdaQueryWrapper<PddGoodsPublishJobItemPO>()
.eq(PddGoodsPublishJobItemPO::getJobId, job.getId())
.eq(PddGoodsPublishJobItemPO::getStatus, PddGoodsPublishJobItemPO.STATUS_FAILED));
job.setSuccessCount((int) ok);
job.setFailCount((int) bad);
job.setStatus(ok == 0 ? PddGoodsPublishJobPO.STATUS_FAILED : PddGoodsPublishJobPO.STATUS_PARTIAL);
job.setMessage(reason);
job.setFinishedAt(now);
jobMapper.updateById(job);
}
/** 异步线程恢复请求侧登录态,供 publish 内 CurrentUserContext 使用 */
private void runWithAuth(Authentication authentication, Runnable action) {
SecurityContext previous = SecurityContextHolder.getContext();
try {
SecurityContext ctx = SecurityContextHolder.createEmptyContext();
ctx.setAuthentication(authentication);
SecurityContextHolder.setContext(ctx);
action.run();
} finally {
SecurityContextHolder.clearContext();
if (previous != null) {
SecurityContextHolder.setContext(previous);
}
}
}
private void process(Long companyId, Long jobId, boolean onlyFailed) {
PddGoodsPublishJobPO job = jobMapper.selectById(jobId);
if (job == null || !companyId.equals(job.getCompanyId())) {
log.error("publish desk job 不存在或公司不匹配,可能事务未提交就启动了异步 companyId={} jobId={}",
companyId, jobId);
return;
}
job.setStatus(PddGoodsPublishJobPO.STATUS_RUNNING);