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
| @Configuration public class KafkaProducerConfiguration { @Bean public ProducerFactory<String, Object> producerFactory() { Map<String, Object> configProps = new HashMap<>(); configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); configProps.put(ProducerConfig.ACKS_CONFIG, "all"); configProps.put(ProducerConfig.RETRIES_CONFIG, 3); configProps.put(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, 1000); configProps.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, 30000); configProps.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384); configProps.put(ProducerConfig.LINGER_MS_CONFIG, 5); configProps.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432); configProps.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy"); configProps.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true); return new DefaultKafkaProducerFactory<>(configProps); } @Bean public KafkaTemplate<String, Object> kafkaTemplate() { KafkaTemplate<String, Object> template = new KafkaTemplate<>(producerFactory()); template.setDefaultTopic("default-topic"); template.setProducerListener(new ProducerListener<String, Object>() { @Override public void onSuccess(ProducerRecord<String, Object> producerRecord, RecordMetadata recordMetadata) { log.info("Message sent successfully: topic={}, partition={}, offset={}", recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset()); } @Override public void onError(ProducerRecord<String, Object> producerRecord, RecordMetadata recordMetadata, Exception exception) { log.error("Failed to send message: {}", producerRecord.value(), exception); } }); return template; } }
@Component public class KafkaEventProducer { @Autowired private KafkaTemplate<String, Object> kafkaTemplate; public CompletableFuture<SendResult<String, Object>> sendEventAsync( String topic, String key, Object event) { ProducerRecord<String, Object> record = new ProducerRecord<>(topic, key, event); record.headers().add("messageId", UUID.randomUUID().toString().getBytes()); record.headers().add("timestamp", String.valueOf(System.currentTimeMillis()).getBytes()); record.headers().add("source", "order-service".getBytes()); return kafkaTemplate.send(record) .addCallback( result -> { if (result != null) { log.info("Event sent successfully: topic={}, partition={}, offset={}", result.getRecordMetadata().topic(), result.getRecordMetadata().partition(), result.getRecordMetadata().offset()); } }, failure -> { log.error("Failed to send event: topic={}, key={}", topic, key, failure); handleSendFailure(topic, key, event, failure); } ); } @Transactional public void sendEventInTransaction(String topic, String key, Object event) { try { kafkaTemplate.executeInTransaction(operations -> { operations.send(topic, key, event); operations.send("audit-topic", key, new AuditEvent(event)); return true; }); log.info("Transactional event sent: topic={}, key={}", topic, key); } catch (Exception e) { log.error("Failed to send transactional event", e); throw e; } } private void handleSendFailure(String topic, String key, Object event, Throwable failure) { FailedMessage failedMessage = new FailedMessage(topic, key, event, failure.getMessage()); failedMessageRepository.save(failedMessage); } }
@Configuration public class KafkaConsumerConfiguration { @Bean public ConsumerFactory<String, Object> consumerFactory() { Map<String, Object> configProps = new HashMap<>(); configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); configProps.put(ConsumerConfig.GROUP_ID_CONFIG, "order-service-group"); configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); configProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); configProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); configProps.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 100); configProps.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 300000); configProps.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 30000); configProps.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, 3000); configProps.put(JsonDeserializer.TRUSTED_PACKAGES, "com.example.events"); configProps.put(JsonDeserializer.VALUE_DEFAULT_TYPE, "com.example.events.BaseEvent"); return new DefaultKafkaConsumerFactory<>(configProps); } @Bean public ConcurrentKafkaListenerContainerFactory<String, Object> kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory()); factory.setConcurrency(3); factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE); factory.setCommonErrorHandler(new DefaultErrorHandler( new FixedBackOff(1000L, 3L) )); return factory; } }
@Component public class KafkaEventConsumer { @Autowired private OrderService orderService; @KafkaListener( topics = "order-events", groupId = "order-processing-group", containerFactory = "kafkaListenerContainerFactory" ) public void handleOrderEvent( @Payload OrderEvent event, @Header Map<String, Object> headers, Acknowledgment acknowledgment, ConsumerRecord<String, OrderEvent> record) { try { log.info("Received order event: type={}, orderId={}, partition={}, offset={}", event.getEventType(), event.getOrderId(), record.partition(), record.offset()); String messageId = new String((byte[]) headers.get("messageId")); if (messageProcessingService.isProcessed(messageId)) { log.info("Message already processed: {}", messageId); acknowledgment.acknowledge(); return; } switch (event.getEventType()) { case ORDER_CREATED: orderService.processOrderCreated((OrderCreatedEvent) event); break; case ORDER_CANCELLED: orderService.processOrderCancelled((OrderCancelledEvent) event); break; case ORDER_COMPLETED: orderService.processOrderCompleted((OrderCompletedEvent) event); break; default: log.warn("Unknown event type: {}", event.getEventType()); } messageProcessingService.markAsProcessed(messageId); acknowledgment.acknowledge(); log.info("Order event processed successfully: {}", event.getOrderId()); } catch (Exception e) { log.error("Failed to process order event: {}", event.getOrderId(), e); if (isRetryableException(e)) { throw e; } else { acknowledgment.acknowledge(); handleNonRetryableError(event, e); } } } private boolean isRetryableException(Exception e) { return e instanceof TransientDataAccessException || e instanceof ConnectException || e instanceof SocketTimeoutException; } private void handleNonRetryableError(OrderEvent event, Exception e) { errorRecordService.recordError(event, e); alertService.sendProcessingErrorAlert(event.getOrderId(), e.getMessage()); } }
|