要連接Kafka集群,需要在Java中進行以下配置:
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>2.8.0</version>
</dependency>
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import java.util.Properties;
public class KafkaProducerExample {
public static void main(String[] args) {
// Kafka集群地址
String kafkaServers = "localhost:9092,localhost:9093,localhost:9094";
// KafkaProducer配置
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServers);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
// 創建KafkaProducer實例
Producer<String, String> producer = new KafkaProducer<>(props);
// 發送消息
// ...
// 關閉KafkaProducer
producer.close();
}
}
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.util.Arrays;
import java.util.Properties;
public class KafkaConsumerExample {
public static void main(String[] args) {
// Kafka集群地址
String kafkaServers = "localhost:9092,localhost:9093,localhost:9094";
// KafkaConsumer配置
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServers);
props.put(ConsumerConfig.GROUP_ID_CONFIG, "my-consumer-group");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
// 創建KafkaConsumer實例
Consumer<String, String> consumer = new KafkaConsumer<>(props);
// 訂閱topic
consumer.subscribe(Arrays.asList("my-topic"));
// 消費消息
// ...
// 關閉KafkaConsumer
consumer.close();
}
}
以上代碼示例中,需要根據實際情況替換kafkaServers
、GROUP_ID_CONFIG
和subscribe
的參數值。kafkaServers
是Kafka集群的地址,GROUP_ID_CONFIG
是消費者組的ID,subscribe
指定要訂閱的topic名稱。
注意:上述代碼示例僅作為演示,實際應用中可能需要配置更多參數,如序列化器、消費位置等。具體配置根據需求來定。