|
27 | 27 | import org.springframework.boot.CommandLineRunner; |
28 | 28 | import org.springframework.context.annotation.Bean; |
29 | 29 | import org.springframework.kafka.core.KafkaTemplate; |
| 30 | +import org.springframework.kafka.support.KafkaHeaders; |
30 | 31 | import org.springframework.kafka.support.SendResult; |
| 32 | +import org.springframework.messaging.Message; |
| 33 | +import org.springframework.messaging.support.MessageBuilder; |
31 | 34 | import org.springframework.retry.annotation.Recover; |
32 | 35 | import org.springframework.stereotype.Service; |
33 | 36 | import org.springframework.transaction.TransactionException; |
|
43 | 46 | @Service |
44 | 47 | @RequiredArgsConstructor |
45 | 48 | public class ProducerService { |
46 | | - private final KafkaTemplate<UUID, SensorEventAvro> kafkaTemplate; |
| 49 | + private final UserRepository userRepository; |
47 | 50 |
|
48 | 51 |
|
49 | | -// @Transactional(value = "transactionManager", rollbackFor = Exception.class) |
| 52 | + private final KafkaTemplate<UUID, SensorEventAvro> sensorEventAvroKafkaTemplate; |
| 53 | + |
| 54 | + @Bean |
| 55 | + public CommandLineRunner commandLineRunner(ProducerService producerService) { |
| 56 | + return args -> { |
| 57 | + for (int i = 0; i < 10; i++) { |
| 58 | + try { |
| 59 | + producerService.process(i); |
| 60 | + } catch (Exception e) { |
| 61 | + System.out.println(e.getMessage()); |
| 62 | + } |
| 63 | + } |
| 64 | + }; |
| 65 | + } |
| 66 | + |
| 67 | + @Transactional(value = "transactionManager", rollbackFor = Exception.class) |
50 | 68 | public void process(int i) throws TransactionException { |
51 | 69 | final SensorEventAvro sensorEvent = new SensorEventAvro(); |
52 | 70 | sensorEvent.setX(i); |
53 | 71 | sensorEvent.setY(Math.random()); |
54 | 72 |
|
| 73 | + SensorEventAvro eventAvro = SensorEventAvro.newBuilder() |
| 74 | + .setId(UUID.randomUUID().toString()) |
| 75 | + .setX(1) |
| 76 | + .setY(Math.random()) |
| 77 | + .build(); |
| 78 | + |
| 79 | + final Message<SensorEventAvro> message = MessageBuilder |
| 80 | + .withPayload(eventAvro) |
| 81 | + .setHeader(KafkaHeaders.KEY, UUID.randomUUID()) |
| 82 | + .setHeader(KafkaHeaders.TOPIC, TopicConfiguration.SENSOR) |
| 83 | + .setHeader(KafkaHeaders.TIMESTAMP, System.currentTimeMillis()) |
| 84 | + .build(); |
55 | 85 |
|
56 | | - CompletableFuture<? extends SendResult<UUID, ?>> future = kafkaTemplate.send(TopicConfiguration.SENSOR, UUID.randomUUID(), sensorEvent); |
| 86 | + CompletableFuture<? extends SendResult<UUID, ?>> future = sensorEventAvroKafkaTemplate.send(message); |
57 | 87 | future.thenAccept(uuidSendResult -> { |
58 | 88 | log.info("Message sent successfully."); |
59 | 89 | }).exceptionally(exception -> { |
|
0 commit comments