【发布时间】:2021-04-25 00:36:39
【问题描述】:
在 windows 机器上,我创建了一个启动并运行的 Kafka 容器。我可以使用以下生产者 java 代码将消息发布到 Kafka 主题。
public static void main(String[] args) {
// Assign topicName to string variable
String topicName = "ms-txnclassification-inbox-topic";
// create instance for properties to access producer configs
Properties props = new Properties();
// Assign localhost id
props.put("bootstrap.servers", "kafka:29092");
// Set acknowledgements for producer requests.
props.put("acks", "all");
// If the request fails, the producer can automatically retry,
props.put("retries", 1);
// Specify buffer size in config
props.put("batch.size", 16384);
// Reduce the no of requests less than 0
props.put("linger.ms", 1);
// The buffer.memory controls the total amount of memory available to the
// producer for buffering.
props.put("buffer.memory", 33554432);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
try (KafkaProducer<String, String> producer = new KafkaProducer(props)){
for (int i = 0; i < 2; i++) {
try {
ProducerRecord<String, String> message1 = new ProducerRecord<>(topicName, Integer.toString(100), Integer.toString(100));
producer.send(message1);
System.out.println("Value sent " + i);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
System.out.println("Failed to deliver message");
}
System.out.println("Message sent successfully");
}
在我将此代码打包成 jar 文件并将其部署到容器中的同时,我无法将消息发布到同一个 Kafka 主题。令人惊讶的是,代码也没有抛出任何错误或异常。
我为发布消息的容器创建的 Dockerfile:
FROM openjdk:8-jre
COPY KafkaTopicTest.jar /app/KafkaTopicTest.jar
一旦这个 docker 容器启动并运行,我手动运行 jar 文件。
java -jar KafkaTopicTest.jar com.temenos.transactionClassificationExecutable.loadTesting.ProducerTesting
注意:当我在容器中 ping kafka 时,我得到了成功的响应。
# ping kafka
PING kafka (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.042 ms
64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.079 ms
64 bytes from localhost (127.0.0.1): icmp_seq=3 ttl=64 time=0.076 ms
^C
--- kafka ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2113ms
rtt min/avg/max/mdev = 0.042/0.065/0.079/0.016 ms
#
不知道哪里出错了!!
【问题讨论】:
-
看起来您是从自身 ping kafka,而不是另一个容器。不知道应该显示什么......你是什么意思“手动运行 JAR”?
标签: java docker apache-kafka kafka-producer-api