最近,在写关于Kafka的消费端代码,发现若要消费,需要登录的时候,对对端Kafka服务进行认证,研究了一番,以下将代码放出来
参考了文章
// 注意 kafka_client_jaas.conf 是认证登录配置文件,里面记录使用了什么登录方式和登录账号密码
// 如果没有这个文件,程序运行的时候可能没有任何提示并且无法消费数据!
System.setProperty("java.security.auth.login.config","kafka_client_jaas.conf");
Properties props = new Properties();
props.put("bootstrap.servers", "xxx.xxx.xxx.xxx");
props.put("group.id", UUID.randomUUID().toString());
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("key.deserializer", StringDeserializer.class.getName());
props.put("value.deserializer", StringDeserializer.class.getName());
props.put("auto.offset.reset","earliest");
//加密传输协议
props.put("security.protocol","SASL_PLAINTEXT");
//加密方式
props.put("sasl.mechanism","SCRAM-SHA-256");
//载入参数
KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String,String>(props);
kafka_client_jaas.conf 文件配置
KafkaClient {
org.apache.kafka.common.security.plain.PlainLoginModule required
username="XXXX"
password="XXXX";
};
注意!
这里演示的是使用了
org.apache.kafka.common.security.plain.PlainLoginModule 模块
也有可能会使用其他模块,例如我项目需要用到
org.apache.kafka.common.security.scram.ScramLoginModule
如果使用了错误模块,运行程序的时候可能没有任何提示,并且不能消费数据!