package com.example.st.kafka;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.util.Properties;
/**
* @Version: 1.0
*/
public class ProductKafkaKerberos {
public static void main(String[] args) {
String filePath = System.getProperty("user.dir") + "\\conf\\";
System.setProperty("java.security.auth.login.config", filePath + "kafka_client_jaas.conf");
System.setProperty("java.security.krb5.conf", filePath + "krb5.conf");
Properties props = new Properties();
props.put("bootstrap.servers", "node1:9092");
props.put("acks", "-1");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
// sasl
props.put("jaas.enabled", true);
props.put("sasl.mechanism", "GSSAPI");
props.put("security.protocol", "SASL_PLAINTEXT");
props.put("sasl.kerberos.service.name", "kafka");
Producer<String, String> producer = new KafkaProducer<>(props);
for (int i = 0; i < 3; i++) {
producer.send(new ProducerRecord<String, String>("test1", Integer.toString(i), Integer.toString(i)));
}
System.out.println("producer is success");
producer.close();
}
}
package com.example.st.kafka;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
/**
* @Version: 1.0
*/
public class ConsumertKafkaKerberos {
public static void main(String[] args) {
String filePath = System.getProperty("user.dir") + "\\conf\\";
System.setProperty("java.security.auth.login.config", filePath + "kafka_client_jaas.conf");
System.setProperty("java.security.krb5.conf", filePath + "krb5.conf");
Properties props = new Properties();
props.put("bootstrap.servers", "node1:9092");
props.put("group.id", "test_group");
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
// sasl
props.put("sasl.mechanism", "GSSAPI");
props.put("security.protocol", "SASL_PLAINTEXT");
props.put("sasl.kerberos.service.name", "kafka");
@SuppressWarnings("resource")
KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
String topic = "test1";
consumer.subscribe(Arrays.asList(topic));
while (true) {
try {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
for (ConsumerRecord<String, String> record : records) {
System.out.printf("offset = %d, partition = %d, key = %s, value = %s%n",
record.offset(), record.partition(), record.key(), record.value());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}