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
   | 
 
  @Service public class OptimizedDataProcessor {          private static final Logger logger = LoggerFactory.getLogger(OptimizedDataProcessor.class);               private final Cache<String, List<DataRecord>> cache = Caffeine.newBuilder()         .maximumSize(1000)         .expireAfterWrite(30, TimeUnit.MINUTES)         .build();               private final Set<String> processingTasks = ConcurrentHashMap.newKeySet();          @Autowired     private DataRepository dataRepository;          @Value("${batch.size:1000}")     private int batchSize;          @Scheduled(fixedRate = 300000)     public void processBatchDataOptimized() {         logger.info("开始优化的批量数据处理");                  try {                          long totalCount = dataRepository.count();             int totalPages = (int) Math.ceil((double) totalCount / batchSize);                          logger.info("总数据量: {}, 分{}页处理,每页{}条", totalCount, totalPages, batchSize);                          for (int page = 0; page < totalPages; page++) {                 processDataPage(page);                                                   if (page % 10 == 0) {                     System.gc();                     Thread.sleep(1000);                  }             }                      } catch (Exception e) {             logger.error("批量处理异常", e);         } finally {                          cleanupResources();         }     }          private void processDataPage(int page) {         Pageable pageable = PageRequest.of(page, batchSize);         Page<DataRecord> dataPage = dataRepository.findAll(pageable);                  logger.debug("处理第{}页,数据量: {}", page + 1, dataPage.getContent().size());                  for (DataRecord record : dataPage.getContent()) {             String taskId = "task_" + record.getId();                          if (processingTasks.contains(taskId)) {                 continue;              }                          processingTasks.add(taskId);                          try {                                  processRecordOptimized(record);                                                   updateCache(record);                              } finally {                 processingTasks.remove(taskId);             }         }     }          private void processRecordOptimized(DataRecord record) {                  String processedData = processDataEfficiently(record.getData());         record.setProcessedData(processedData);                           dataRepository.save(record);     }          private String processDataEfficiently(String data) {                  StringBuilder result = new StringBuilder(data.length() * 2);                           for (int i = 0; i < 100; i++) {              result.append(data).append("_").append(i);         }                  return result.toString();     }          private void updateCache(DataRecord record) {         String category = record.getCategory();                           List<DataRecord> categoryRecords = cache.get(category,              k -> new ArrayList<>());                           if (categoryRecords.size() < 100) {             categoryRecords.add(record);         }     }          private void cleanupResources() {                  processingTasks.clear();         cache.invalidateAll();                  logger.info("资源清理完成");     }               @GetMapping("/memory/status")     public ResponseEntity<Map<String, Object>> getMemoryStatus() {         Map<String, Object> status = new HashMap<>();                  status.put("cache_size", cache.estimatedSize());         status.put("processing_tasks", processingTasks.size());                           MemoryUsage heapUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();         status.put("heap_used_mb", heapUsage.getUsed() / 1024 / 1024);         status.put("heap_max_mb", heapUsage.getMax() / 1024 / 1024);         status.put("heap_usage_percent",              String.format("%.2f", (double) heapUsage.getUsed() / heapUsage.getMax() * 100));                  return ResponseEntity.ok(status);     } }
 
  """ java -Xms4g -Xmx8g       -XX:+UseG1GC       -XX:MaxGCPauseMillis=100       -XX:G1HeapRegionSize=16m      -XX:+PrintGC       -XX:+PrintGCDetails       -XX:+PrintGCTimeStamps      -XX:+HeapDumpOnOutOfMemoryError      -XX:HeapDumpPath=/app/logs/      -jar data-processor.jar """
 
  |