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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
|
@Service public class KafkaGPSDataProcessingService { @Autowired private KafkaGPSDataProperties properties; @Autowired private KafkaTemplate<String, GPSData> gpsDataKafkaTemplate; @Autowired private KafkaGPSDataMonitorService kafkaGPSDataMonitorService; @Autowired private KafkaAdmin kafkaAdmin; private static final Logger logger = LoggerFactory.getLogger(KafkaGPSDataProcessingService.class);
public KafkaGPSDataSendResult sendGPSData(GPSData gpsData) { logger.info("发送GPS数据到Kafka,车辆ID: {}, 消息ID: {}", gpsData.getVehicleId(), gpsData.getMessageId()); KafkaGPSDataSendResult result = new KafkaGPSDataSendResult(); result.setMessageId(gpsData.getMessageId()); result.setVehicleId(gpsData.getVehicleId()); result.setStartTime(System.currentTimeMillis()); try { if (!gpsData.validate()) { result.setSuccess(false); result.setError("GPS数据验证失败"); result.setEndTime(System.currentTimeMillis()); return result; } gpsData.setDataQuality(gpsData.calculateDataQuality()); String partitionKey = gpsData.generatePartitionKey(); gpsData.setPartitionKey(partitionKey); ListenableFuture<SendResult<String, GPSData>> future = gpsDataKafkaTemplate.send( properties.getTopicName(), partitionKey, gpsData); future.addCallback( result -> { logger.debug("GPS数据发送成功,车辆ID: {}, 分区: {}, 偏移量: {}", gpsData.getVehicleId(), result.getRecordMetadata().partition(), result.getRecordMetadata().offset()); }, failure -> { logger.error("GPS数据发送失败,车辆ID: {}", gpsData.getVehicleId(), failure); } ); SendResult<String, GPSData> sendResult = future.get(5, TimeUnit.SECONDS); result.setSuccess(true); result.setPartition(sendResult.getRecordMetadata().partition()); result.setOffset(sendResult.getRecordMetadata().offset()); result.setEndTime(System.currentTimeMillis()); kafkaGPSDataMonitorService.recordGPSDataSend(gpsData.getVehicleId(), true); logger.info("GPS数据发送成功,车辆ID: {}, 分区: {}, 偏移量: {}, 耗时: {}ms", gpsData.getVehicleId(), result.getPartition(), result.getOffset(), result.getDuration()); return result; } catch (Exception e) { logger.error("GPS数据发送异常,车辆ID: {}", gpsData.getVehicleId(), e); result.setSuccess(false); result.setError("GPS数据发送异常: " + e.getMessage()); result.setEndTime(System.currentTimeMillis()); kafkaGPSDataMonitorService.recordGPSDataSend(gpsData.getVehicleId(), false); return result; } }
public KafkaGPSDataBatchSendResult batchSendGPSData(List<GPSData> gpsDataList) { logger.info("批量发送GPS数据到Kafka,数量: {}", gpsDataList.size()); KafkaGPSDataBatchSendResult result = new KafkaGPSDataBatchSendResult(); result.setTotalCount(gpsDataList.size()); result.setStartTime(System.currentTimeMillis()); try { List<List<GPSData>> batches = partitionList(gpsDataList, properties.getProducer().getBatchSize() / 100); for (List<GPSData> batch : batches) { List<CompletableFuture<KafkaGPSDataSendResult>> futures = batch.stream() .map(gpsData -> CompletableFuture.supplyAsync(() -> sendGPSData(gpsData))) .collect(Collectors.toList()); CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); for (CompletableFuture<KafkaGPSDataSendResult> future : futures) { KafkaGPSDataSendResult sendResult = future.get(); if (sendResult.isSuccess()) { result.incrementSuccessCount(); } else { result.incrementFailureCount(); } } } result.setEndTime(System.currentTimeMillis()); kafkaGPSDataMonitorService.recordGPSDataBatchSend(gpsDataList.size(), result.getSuccessCount()); logger.info("批量GPS数据发送完成,总数: {}, 成功: {}, 失败: {}, 耗时: {}ms", result.getTotalCount(), result.getSuccessCount(), result.getFailureCount(), result.getDuration()); return result; } catch (Exception e) { logger.error("批量GPS数据发送异常", e); result.setSuccess(false); result.setError("批量GPS数据发送异常: " + e.getMessage()); result.setEndTime(System.currentTimeMillis()); return result; } }
public KafkaTopicCreateResult createGPSDataTopic() { logger.info("创建GPS数据主题,主题名: {}", properties.getTopicName()); KafkaTopicCreateResult result = new KafkaTopicCreateResult(); result.setTopicName(properties.getTopicName()); result.setStartTime(System.currentTimeMillis()); try { if (topicExists(properties.getTopicName())) { result.setSuccess(true); result.setMessage("主题已存在"); result.setEndTime(System.currentTimeMillis()); return result; } NewTopic newTopic = new NewTopic(properties.getTopicName(), properties.getTopicPartitions(), (short) properties.getTopicReplicationFactor()); CreateTopicsResult createTopicsResult = kafkaAdmin.createTopics(Collections.singletonList(newTopic)); createTopicsResult.all().get(30, TimeUnit.SECONDS); result.setSuccess(true); result.setPartitions(properties.getTopicPartitions()); result.setReplicationFactor(properties.getTopicReplicationFactor()); result.setEndTime(System.currentTimeMillis()); logger.info("GPS数据主题创建成功,主题名: {}, 分区数: {}, 副本数: {}", properties.getTopicName(), properties.getTopicPartitions(), properties.getTopicReplicationFactor()); return result; } catch (Exception e) { logger.error("GPS数据主题创建异常,主题名: {}", properties.getTopicName(), e); result.setSuccess(false); result.setError("GPS数据主题创建异常: " + e.getMessage()); result.setEndTime(System.currentTimeMillis()); return result; } }
private boolean topicExists(String topicName) { try { ListTopicsResult listTopicsResult = kafkaAdmin.listTopics(); Set<String> topicNames = listTopicsResult.names().get(10, TimeUnit.SECONDS); return topicNames.contains(topicName); } catch (Exception e) { logger.error("检查主题是否存在异常,主题名: {}", topicName, e); return false; } }
public KafkaTopicInfo getTopicInfo(String topicName) { try { DescribeTopicsResult describeTopicsResult = kafkaAdmin.describeTopics(Collections.singletonList(topicName)); Map<String, TopicDescription> topicDescriptions = describeTopicsResult.all().get(10, TimeUnit.SECONDS); TopicDescription topicDescription = topicDescriptions.get(topicName); if (topicDescription != null) { KafkaTopicInfo topicInfo = new KafkaTopicInfo(); topicInfo.setTopicName(topicName); topicInfo.setPartitions(topicDescription.partitions().size()); topicInfo.setReplicationFactor(topicDescription.partitions().get(0).replicas().size()); topicInfo.setInternal(topicDescription.isInternal()); return topicInfo; } return null; } catch (Exception e) { logger.error("获取主题信息异常,主题名: {}", topicName, e); return null; } }
private <T> List<List<T>> partitionList(List<T> list, int size) { List<List<T>> partitions = new ArrayList<>(); for (int i = 0; i < list.size(); i += size) { partitions.add(list.subList(i, Math.min(i + size, list.size()))); } return partitions; } }
|