kafka 动态认证 权限认证 生产者 消费者 订阅发布-亲测成功
kafka权限认证 topic权限认证 权限动态认证-亲测成功
kafka连接认证
连接kafka时的自定义认证请看如下博文
生产者
废话不多说,直接上代码,如下是生产者代码
public static void main(String[] args) {
Properties props = new Properties();
props.put("bootstrap.servers", "192.168.12.1:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
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");
String username = "liang";
String password = "123456";
// 配置 SASL 认证属性
props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
props.put(SaslConfigs.SASL_MECHANISM, "PLAIN");
props.put(SaslConfigs.SASL_JAAS_CONFIG,
"org.apache.kafka.common.security.plain.PlainLoginModule required\n" +
"username=\"" + username + "\"\n" +
"password=\"" + password + "\";");
Producer<String, String> producer = new KafkaProducer<>(props);
for (int i = 0; i < 10; i++) {
producer.send(new ProducerRecord<String, String>("queueTopic", Integer.toString(i), Integer.toString(i)));
}
producer.close();
}
消费者
废话不多说,直接上代码,如下是消费者代码
public static void main(String[] args) {
try {
Properties props = new Properties();
props.put("bootstrap.servers", "192.168.12.1:9092");
props.put("group.id", "default_group");
props.put("auto.offset.reset", "earliest");
//策略1 自动提交,周期性的提交偏移量
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
//策略2 consumer.commitSync() //调用commitSync,手动同步ack。每处理完1条消息,commitSync 1次
//策略3 consumer.commitASync() //手动异步ack
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
String username = "liang";
String password = "123456";
// 配置 SASL 认证属性
props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
props.put(SaslConfigs.SASL_MECHANISM, "PLAIN");
props.put(SaslConfigs.SASL_JAAS_CONFIG,
"org.apache.kafka.common.security.plain.PlainLoginModule required\n" +
"username=\"" + username + "\"\n" +
"password=\"" + password + "\";");
KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(props);
kafkaConsumer.subscribe(Arrays.asList("queueTopic"));
boolean flag = true;
while (flag) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(100);
for (ConsumerRecord<String, String> record : records) {
logger.info("=====================================offset = {},key = {},value = {}", record.offset(), record.key(), record.value());
}
}
kafkaConsumer.close();
logger.info("consumer client has been closed");
} catch (Exception e) {
logger.error("{}", e.getMessage());
}
}