Created
March 28, 2024 09:28
-
-
Save serdarmumcu/5a9b8c2542f250994e875408fe07ddf2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Service | |
public class EventPublisherService { | |
@Autowired | |
private OutboxRepository outboxRepository; | |
@Autowired | |
private KafkaTemplate<String, String> kafkaTemplate; | |
@Autowired | |
private EventProcessingService eventProcessingService; | |
@Scheduled(fixedDelay = 10000) | |
public void publishEvents() { | |
List<Outbox> events = outboxRepository.findAll(); | |
List<Long> eventIdsForDeletion = new ArrayList<>(); | |
CompletableFuture<?>[] futures = events.stream().map(event -> | |
kafkaTemplate.send("messages-topic", event.getPayload()).thenApply(sendResult -> { | |
synchronized (eventIdsForDeletion) { | |
eventIdsForDeletion.add(event.getId()); | |
} | |
return null; | |
}).exceptionally(throwable -> { | |
// Log error or implement retry mechanism | |
System.out.println("Error sending event to Kafka: " + throwable.getMessage()); | |
return null; | |
}) | |
).toArray(CompletableFuture[]::new); | |
CompletableFuture.allOf(futures).join(); | |
eventProcessingService.deleteProcessedEvents(eventIdsForDeletion); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment