|
13 | 13 | import org.springframework.data.domain.Pageable; |
14 | 14 | import org.springframework.scheduling.annotation.Scheduled; |
15 | 15 | import org.springframework.stereotype.Service; |
| 16 | +import org.springframework.transaction.annotation.Transactional; |
16 | 17 | import org.springframework.util.StopWatch; |
17 | 18 |
|
18 | 19 | import java.time.LocalDateTime; |
@@ -99,6 +100,7 @@ public class DataSyncScheduler { |
99 | 100 | private com.phantoms.phantomsbackend.repository.secondary.SecondaryExpeditionaryTeamRepository secondaryExpeditionaryTeamRepository; |
100 | 101 |
|
101 | 102 | @Scheduled(fixedRate = 600000) // 每10分钟执行一次 |
| 103 | + @Transactional(timeout = 300) |
102 | 104 | public void syncData() { |
103 | 105 | StopWatch totalStopWatch = new StopWatch("TotalSync"); |
104 | 106 | totalStopWatch.start("total-sync"); |
@@ -252,41 +254,29 @@ private List<com.phantoms.phantomsbackend.pojo.entity.secondary.onebot.ChatRecor |
252 | 254 | } |
253 | 255 |
|
254 | 256 | /** |
255 | | - * 优化后的批量插入方法 |
| 257 | + * 优化后的批量插入方法 - 使用 Spring 事务管理 |
256 | 258 | */ |
| 259 | + @Transactional(timeout = 120) // 2分钟超时 |
257 | 260 | private void batchInsertOptimized(List<com.phantoms.phantomsbackend.pojo.entity.secondary.onebot.ChatRecord> records) { |
258 | 261 | if (records.isEmpty()) { |
259 | 262 | return; |
260 | 263 | } |
261 | 264 |
|
262 | | - EntityManager entityManager = entityManagerFactory.createEntityManager(); |
263 | | - EntityTransaction transaction = entityManager.getTransaction(); |
264 | | - |
265 | 265 | try { |
266 | | - transaction.begin(); |
267 | | - |
| 266 | + // 使用 Spring Data JPA 的批量保存 |
268 | 267 | for (int i = 0; i < records.size(); i++) { |
269 | | - entityManager.persist(records.get(i)); |
| 268 | + secondaryChatRecordRepository.save(records.get(i)); |
270 | 269 |
|
271 | 270 | // 分批刷新,避免内存溢出 |
272 | 271 | if ((i + 1) % INSERT_BATCH_SIZE == 0) { |
273 | | - entityManager.flush(); |
274 | | - entityManager.clear(); |
| 272 | + secondaryChatRecordRepository.flush(); |
275 | 273 | } |
276 | 274 | } |
277 | | - |
278 | | - entityManager.flush(); |
279 | | - entityManager.clear(); |
280 | | - transaction.commit(); |
| 275 | + secondaryChatRecordRepository.flush(); |
281 | 276 |
|
282 | 277 | } catch (Exception e) { |
283 | | - if (transaction.isActive()) { |
284 | | - transaction.rollback(); |
285 | | - } |
286 | 278 | logger.error("Batch insert failed for {} records", records.size(), e); |
287 | 279 | throw e; |
288 | | - } finally { |
289 | | - entityManager.close(); |
290 | 280 | } |
291 | 281 | } |
292 | 282 |
|
|
0 commit comments