1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
|
@Component @Slf4j public class BatchProcessor {
private final DataSplitter dataSplitter; private final ChunkProcessor chunkProcessor; private final BatchValidator batchValidator;
private final AtomicLong totalBatchesProcessed = new AtomicLong(0); private final AtomicLong totalItemsProcessed = new AtomicLong(0); private final AtomicLong totalProcessingTime = new AtomicLong(0);
public <T> List<List<T>> splitData(List<T> data, int batchSize) { try { if (data == null || data.isEmpty()) { return new ArrayList<>(); }
if (batchSize <= 0) { batchSize = 100; }
List<List<T>> batches = dataSplitter.split(data, batchSize);
log.debug("数据分割完成: 总数量={}, 批次大小={}, 批次数量={}", data.size(), batchSize, batches.size());
return batches;
} catch (Exception e) { log.error("数据分割失败", e); throw new BatchProcessorException("数据分割失败: " + e.getMessage()); } }
public <T, R> BatchResult<R> processBatch(List<T> batch, BatchItemProcessor<T, R> processor) { try { long startTime = System.currentTimeMillis();
if (!batchValidator.validate(batch)) { throw new BatchProcessorException("批次验证失败"); }
List<R> results = new ArrayList<>(); List<Exception> exceptions = new ArrayList<>(); int successCount = 0; int failureCount = 0;
for (int i = 0; i < batch.size(); i++) { T item = batch.get(i);
try { R result = processor.process(item); results.add(result); successCount++;
} catch (Exception e) { log.error("处理单个项目失败: 批次索引={}, 项目索引={}", batch.hashCode(), i, e); exceptions.add(e); failureCount++; } }
long endTime = System.currentTimeMillis(); long processingTime = endTime - startTime;
totalBatchesProcessed.incrementAndGet(); totalItemsProcessed.addAndGet(batch.size()); totalProcessingTime.addAndGet(processingTime);
BatchResult<R> result = BatchResult.<R>builder() .batchIndex(batch.hashCode()) .successCount(successCount) .failureCount(failureCount) .results(results) .exceptions(exceptions) .processingTime(processingTime) .build();
log.debug("批次处理完成: 批次大小={}, 成功数量={}, 失败数量={}, 处理时间={}ms", batch.size(), successCount, failureCount, processingTime);
return result;
} catch (Exception e) { log.error("批次处理失败", e); throw new BatchProcessorException("批次处理失败: " + e.getMessage(), e); } }
public <T, R> List<BatchResult<R>> processBatchesParallel(List<List<T>> batches, BatchItemProcessor<T, R> processor, int parallelism) { try { if (batches == null || batches.isEmpty()) { return new ArrayList<>(); }
if (parallelism <= 0) { parallelism = Runtime.getRuntime().availableProcessors(); }
ExecutorService executor = Executors.newFixedThreadPool(parallelism);
try { List<CompletableFuture<BatchResult<R>>> futures = batches.stream() .map(batch -> CompletableFuture.supplyAsync(() -> processBatch(batch, processor), executor)) .collect(Collectors.toList());
List<BatchResult<R>> results = futures.stream() .map(CompletableFuture::join) .collect(Collectors.toList());
log.info("并行批次处理完成: 批次数量={}, 并行度={}", batches.size(), parallelism);
return results;
} finally { executor.shutdown(); }
} catch (Exception e) { log.error("并行批次处理失败", e); throw new BatchProcessorException("并行批次处理失败: " + e.getMessage(), e); } }
public <T, R> List<BatchResult<R>> processBatchesPipeline(List<List<T>> batches, BatchItemProcessor<T, R> processor, int pipelineSize) { try { if (batches == null || batches.isEmpty()) { return new ArrayList<>(); }
if (pipelineSize <= 0) { pipelineSize = 3; }
List<BatchResult<R>> results = new ArrayList<>(); BlockingQueue<List<T>> inputQueue = new LinkedBlockingQueue<>(pipelineSize); BlockingQueue<BatchResult<R>> outputQueue = new LinkedBlockingQueue<>(pipelineSize);
Thread producer = new Thread(() -> { try { for (List<T> batch : batches) { inputQueue.put(batch); } inputQueue.put(new ArrayList<>()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } });
Thread consumer = new Thread(() -> { try { List<T> batch; while ((batch = inputQueue.take()) != null && !batch.isEmpty()) { BatchResult<R> result = processBatch(batch, processor); outputQueue.put(result); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } });
producer.start(); consumer.start();
BatchResult<R> result; while ((result = outputQueue.take()) != null) { results.add(result); }
producer.join(); consumer.join();
log.info("流水线批次处理完成: 批次数量={}, 流水线大小={}", batches.size(), pipelineSize);
return results;
} catch (Exception e) { log.error("流水线批次处理失败", e); throw new BatchProcessorException("流水线批次处理失败: " + e.getMessage(), e); } }
public BatchProcessingStatistics getStatistics() { try { long totalBatches = totalBatchesProcessed.get(); long totalItems = totalItemsProcessed.get(); long totalTime = totalProcessingTime.get();
return BatchProcessingStatistics.builder() .totalBatchesProcessed(totalBatches) .totalItemsProcessed(totalItems) .totalProcessingTime(totalTime) .averageBatchSize(totalBatches > 0 ? (double) totalItems / totalBatches : 0) .averageProcessingTime(totalBatches > 0 ? (double) totalTime / totalBatches : 0) .build();
} catch (Exception e) { log.error("获取处理统计信息失败", e); throw new BatchProcessorException("获取处理统计信息失败: " + e.getMessage()); } } }
|