以下示例给你一份“能直接放进项目里跑起来”的 80 % 骨架,其余 20 %(FTP 连接细节、第三方比对 API 的 DTO 等)按你们公司的实际情况补充即可。示例全部符合 Java 8 + Spring-Boot 2.1.3 + reactor-core 3.3.0 + netty-all 4.1.9.Final 的依赖约束,不用 Redis,任务完全保存在内存,可被取消/可重试,支持多用户并发,结构尽量靠拢 DDD + SOLID。
1. 依赖 & 基础配置
<!-- pom.xml 片段 -->
<properties>
<java.version>1.8</java.version>
<spring.boot.version>2.1.3.RELEASE</spring.boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<!-- STOMP over WebSocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- JPA 仅用于查询附件表 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- DB 驱动、FTP、测试、断言、重试 -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version><!-- 够用的 FTP 客户端 -->
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>3.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-retry</artifactId>
<version>1.7.1</version>
</dependency>
<!-- 测试 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.2.0</version>
<scope>test</scope>
</dependency>
</dependencies>
# application.yml
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/yourdb?characterEncoding=UTF-8
username: root
password: root
jpa:
hibernate:
ddl-auto: none
logging:
level:
root: info
2. 领域模型(DDD)
+------------------+
| TaskAggregate | (任务聚合根)
+------------------+
| taskId |
| userId |
| status | (RUNNING/FAILED/...)
| progress 1..100 |
| cancelFlag | (AtomicBoolean)
| subTasks[] | (Value Object)
+------------------+
SubTask:
+ fileInfo
+ status (SUCCESS/FAILED/CANCELLED/TIMEOUT)
+ result (返回的匹配结果)
Repository:
InMemoryTaskRepository (线程安全 ConcurrentHashMap)
Service:
TaskCommandService (创建/取消/查询)
TaskExecutorService (真正做事)
Event:
TaskEvent -> 推送给前端 (STOMP)
Factory:
SubTaskFactory (根据 DB 查询结果产出子任务)
策略(Strategy):
RetryStrategy / CancelStrategy / FtpClientStrategy
3. 线程池区分 & 取消策略
@Configuration
public class ExecutorConfig {
// IO 密集(FTP、HTTP 调第三方接口)
@Bean(name = "ioExecutor")
public Executor ioExecutor() {
return Executors.newFixedThreadPool(
Math.max(16, Runtime.getRuntime().availableProcessors() * 2),
new NamedThreadFactory("io-pool-"));
}
// CPU 密集(解析文本、计算对比结果)
@Bean(name = "cpuExecutor")
public Executor cpuExecutor() {
return Executors.newWorkStealingPool();
}
}
取消思路:
- TaskAggregate 内部维护
AtomicBoolean cancelled.
- 每个
SubTaskRunner 周期性检查 cancelled.get();如 true 则 throw new CancellationException.
- 取消操作不会立刻
shutdownNow() 线程池,而是写入 cancelled=true,让 1 min 内不会再生成新的 SubTask,同时正在跑的 SubTask 在第一处检查点被中断退出。
4. 核心代码
4.1. Domain 对象
@Data
@AllArgsConstructor
@Builder
public class TaskAggregate {
private final String taskId;
private final Long userId;
private final AtomicBoolean cancelled = new AtomicBoolean(false);
private volatile TaskStatus status; // RUNNING ...
private final AtomicInteger success = new AtomicInteger();
private final AtomicInteger failed = new AtomicInteger();
private final AtomicInteger cancelledCount = new AtomicInteger();
private final int total;
private final AtomicInteger finished = new AtomicInteger();
private volatile int progress;
public boolean cancel() {
return cancelled.compareAndSet(false, true);
}
}
4.2. In-Memory Repository
@Component
public class InMemoryTaskRepository {
private final ConcurrentMap<String, TaskAggregate> store = new ConcurrentHashMap<>();
public void save(TaskAggregate task){ store.put(task.getTaskId(), task);}
public Optional<TaskAggregate> find(String id){ return Optional.ofNullable(store.get(id));}
public void remove(String id){ store.remove(id);}
}
4.3. 创建任务命令
@Service
@RequiredArgsConstructor
public class TaskCommandService {
private final InMemoryTaskRepository repo;
private final SubTaskFactory factory;
private final TaskExecutorService executor;
public String createTask(Long userId, Long fileId, int size) {
List<SubTask> subTasks = factory.build(fileId, size);
String taskId = UUID.randomUUID().toString();
TaskAggregate agg = TaskAggregate.builder()
.taskId(taskId)
.userId(userId)
.status(TaskStatus.RUNNING)
.total(subTasks.size())
.progress(0)
.build();
repo.save(agg);
executor.execute(agg, subTasks);
return taskId;
}
public void cancelTask(Long userId, String taskId){
TaskAggregate agg = repo.find(taskId)
.filter(t -> t.getUserId().equals(userId))
.orElseThrow(() -> new IllegalArgumentException("not found"));
agg.cancel();
}
}
4.4. SubTaskFactory(查询数据库)
@Repository
public interface AttachmentJpa extends JpaRepository<Attachment, Long> {
@Query("select a from Attachment a where a.type in ('doc','docx')"
+ " and a.latest = true and a.fileId <> :fileId"
+ " and a.filename not in (select filename from Attachment where fileId=:fileId)"
+ " order by a.id desc")
List<Attachment> pick(@Param("fileId") Long fileId, Pageable pageable);
}
@Component
@RequiredArgsConstructor
public class SubTaskFactory {
private final AttachmentJpa jpa;
public List<SubTask> build(Long fileId, int size){
List<Attachment> list = jpa.pick(fileId, PageRequest.of(0, size));
return list.stream()
.map(att -> new SubTask(att.getFtpPath(), att.getFilename()))
.collect(Collectors.toList());
}
}
4.5. TaskExecutorService(关键)
@Service
@RequiredArgsConstructor
@Slf4j
public class TaskExecutorService {
private final Executor ioExecutor;
private final Executor cpuExecutor;
private final StompNotifier notifier;
private final InMemoryTaskRepository repo;
private final Retry retry = Retry.ofDefaults("ftpRetry");
public void execute(TaskAggregate agg, List<SubTask> subTasks){
// 1. 把 SubTask 转换为 Flux
Flux.fromIterable(subTasks)
.flatMap(subTask -> runSubTask(agg, subTask)
.subscribeOn(Schedulers.fromExecutor(ioExecutor)), 16) // 并行度 16
.doOnError(e -> {agg.setStatus(TaskStatus.FAILED);})
.doOnComplete(() -> {
agg.setStatus(TaskStatus.COMPLETED);
notifier.sendFinished(agg);
})
.subscribe(); // Fire
}
private Mono<Void> runSubTask(TaskAggregate agg, SubTask subTask){
return Mono.fromCallable(() -> {
if (agg.getCancelled().get()) {
subTask.setStatus(SubTaskStatus.CANCELLED);
agg.getCancelledCount().incrementAndGet();
throw new CancellationException();
}
// 1. 取 FTP 文本
String text = retry.executeCallable(() -> FtpUtils.read(subTask.getFtpPath()));
// 2. 调第三方比对 API (异步 HTTP)
String compareResult = ThirdApi.compare(text, subTask.getFileName());
subTask.setResult(compareResult);
subTask.setStatus(SubTaskStatus.SUCCESS);
agg.getSuccess().incrementAndGet();
return compareResult;
})
.flatMap(result -> Mono.fromRunnable(() -> notifier.sendPiece(agg.getTaskId(), subTask, result))
.subscribeOn(Schedulers.fromExecutor(cpuExecutor)))
.onErrorResume(ex -> {
if(ex instanceof CancellationException){
return Mono.empty();
}
subTask.setStatus(SubTaskStatus.FAILED);
agg.getFailed().incrementAndGet();
return Mono.empty();
})
.doFinally(signal -> {
int done = agg.getFinished().incrementAndGet();
agg.setProgress((int)((done * 100.0)/agg.getTotal()));
});
}
}
4.6. STOMP 推送
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
public void registerStompEndpoints(StompEndpointRegistry registry){
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
public void configureMessageBroker(MessageBrokerRegistry config){
config.enableSimpleBroker("/topic/");
config.setApplicationDestinationPrefixes("/app");
}
}
@Component
@RequiredArgsConstructor
public class StompNotifier {
private final SimpMessagingTemplate template;
public void sendPiece(String taskId, SubTask subTask, String result){
template.convertAndSend("/topic/task/"+taskId,
new PieceDTO(subTask.getFileName(), result, subTask.getStatus()));
}
public void sendFinished(TaskAggregate agg){
template.convertAndSend("/topic/task/"+agg.getTaskId()+"/done",
new SummaryDTO(agg.getSuccess().get(), agg.getFailed().get(),
agg.getCancelledCount().get(), agg.getTotal()));
}
}
5. 取消实现细节
TaskCommandService.cancelTask() → agg.cancel()
cancel() 只改 AtomicBoolean。
- 任何新的 SubTask 创建前都会检查
cancelled;已有任务每个关键步骤都检查一次。
- SpringBoot 提供的
Schedulers.fromExecutor(ioExecutor) 会把线程 interruption 传播,Retry 也会在检测到 cancelled 时快速退出。
6. 重试机制
这里使用 resilience4j-retry,默认 3 次指数退避。若想用 Reactor 的 retryBackoff 也行。FtpUtils.read() 若失败就会被 retry.executeCallable(...) 包住自带重试,同样适用于调用第三方接口。
7. 核心设计模式 & SOLID 对应
• Factory:SubTaskFactory 生成子任务避免直接 new。
• Strategy:Retry、FtpClientStrategy 可以替换不同实现。
• Observer:STOMP 推送即事件通知。
• Singleton:InMemoryTaskRepository、Executor Bean。
• Template Method:runSubTask 中留出比对实现可抽象成模板。
SOLID 映射:
S (单一职责) — 每个类只干一件事;
O (开闭) — 策略与模板模式易于扩展;
L (里氏替换) — 接口 + 抽象服务可替换;
I (接口隔离) — 按领域划分接口;
D (依赖反转) — 高层模块(任务服务)依赖抽象(FtpClient、ThirdApi)。
8. TDD 样例
@ExtendWith(MockitoExtension.class)
class TaskCommandServiceTest {
@Mock SubTaskFactory factory;
@Mock TaskExecutorService executor;
@InjectMocks TaskCommandService service;
@Test
void createTask_shouldGenerateTaskAndInvokeExecutor() {
when(factory.build(1L, 2)).thenReturn(Collections.emptyList());
String id = service.createTask(99L, 1L, 2);
assertNotNull(id);
verify(executor).execute(any(TaskAggregate.class), anyList());
}
}
9. 调用流程时序图(浓缩版)
Controller ----> TaskCommandService ----> InMemoryTaskRepository
| | |
| v |
| TaskExecutorService <--------+
| |
| Reactor Flux
| |
v v
STOMP <--------- SubTaskRunner(FTP + API)
10. 操作指令(演示)
- 前端经
/app/task/create 发送 {userId:1,fileId:123,size:100}
- 后端返回
taskId.
- 前端订阅
/topic/task/{taskId} 获取实时子任务结果;订阅 /topic/task/{taskId}/done 获取汇总。
- 想取消时
/app/task/cancel 发送 {userId:1,taskId:"…"}。
🎉 至此,一个可取消、有进度、有重试、纯内存、无 Redis、区分用户、DDD 化的任务系统就搭出来了!如需继续深入(例如跨 JVM 持久化、水平扩展),再把 InMemoryTaskRepository 换成数据库/消息队列即可。