|
| 1 | +package com.example.okafka; |
| 2 | + |
| 3 | +import org.apache.kafka.clients.producer.ProducerRecord; |
| 4 | +import org.oracle.okafka.clients.producer.KafkaProducer; |
| 5 | + |
| 6 | +import java.sql.*; |
| 7 | +import java.time.Instant; |
| 8 | +import java.util.Properties; |
| 9 | + |
| 10 | +import static com.example.okafka.OKafka.TRANSACTIONAL_TOPIC_NAME; |
| 11 | +import static com.example.okafka.OKafkaAuthentication.getAuthenticationProperties; |
| 12 | + |
| 13 | +public class TransactionalProducer { |
| 14 | + public static void main(String[] args) throws InterruptedException, SQLException { |
| 15 | + Properties props = getAuthenticationProperties(); |
| 16 | + props.put("enable.idempotence", "true"); |
| 17 | + props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); |
| 18 | + props.put("value.serializer", "org.apache.kafka.common.serialization.LongSerializer"); |
| 19 | + // This property is required for transactional producers |
| 20 | + props.put("oracle.transactional.producer", "true"); |
| 21 | + KafkaProducer<String, Long> producer = new KafkaProducer<>(props); |
| 22 | + producer.initTransactions(); |
| 23 | + |
| 24 | + int pauseMillis = 1000; |
| 25 | + String pm = System.getenv("PAUSE_MILLIS"); |
| 26 | + if (pm != null && !pm.isEmpty()) { |
| 27 | + pauseMillis = Integer.parseInt(pm); |
| 28 | + } |
| 29 | + |
| 30 | + while (true) { |
| 31 | + Instant now = Instant.now(); |
| 32 | + long id; |
| 33 | + producer.beginTransaction(); |
| 34 | + Connection conn = producer.getDBConnection(); |
| 35 | + |
| 36 | + final String sql = "insert into log (produced) values (?)"; |
| 37 | + try (PreparedStatement ps = conn.prepareStatement(sql, new String[]{"id",})) { |
| 38 | + ps.setDate(1, new Date(now.toEpochMilli())); |
| 39 | + ps.executeUpdate(); |
| 40 | + |
| 41 | + ResultSet generatedKeys = ps.getGeneratedKeys(); |
| 42 | + if (generatedKeys.next()) { |
| 43 | + id = generatedKeys.getLong(1); |
| 44 | + } else { |
| 45 | + throw new SQLException("Create log message failed, no ID obtained"); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + ProducerRecord<String, Long> record = new ProducerRecord<>(TRANSACTIONAL_TOPIC_NAME, id); |
| 50 | + producer.send(record); |
| 51 | + |
| 52 | + producer.commitTransaction(); |
| 53 | + System.out.println("Producer sent message: " + record.value()); |
| 54 | + |
| 55 | + Thread.sleep(pauseMillis); |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments