其实程序很简单
import java.util.Arrays;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
public class Consumer {
public static void main(String[] args) {
Properties props = new Properties();
props.put("bootstrap.servers",
"****:9092");
props.put("group.id", "groupId");
props.put("enable.auto.commit", "false");
props.put("auto.offset.reset", "earliest");
props.put("auto.commit.interval.ms", "1000");
props.put("session.timeout.ms", "30000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("security.protocol", "SASL_SSL");
props.put("ssl.endpoint.identification.algorithm", "");
props.put("ssl.truststore.location", "D:/Kafka/******.jks");
props.put("ssl.truststore.password", "WSO2_sp440");
props.put("sasl.mechanism", "SCRAM-SHA-512");
props.put("sasl.jaas.config",
"org.apache.kafka.common.security.scram.ScramLoginModule required username='account_name' password='pwd';");
@SuppressWarnings("resource")
KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
consumer.subscribe(Arrays.asList("topic_name"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records) {
System.out.printf("partition= %d, offset = %d, key = %s, value = %s\n", record.partition(),
record.offset(), record.key(), record.value());
//consumer.commitSync();
}
}
}
}
但是一直报错
java.lang.IllegalArgumentException: JAAS config entry not terminated by semi-colon
查了很多材料都没有问题,
后来才注意到
props.put("sasl.jaas.config",
"org.apache.kafka.common.security.scram.ScramLoginModule required username='account_name' password='pwd';");
注意观察最后面的是有一个分号的,这个很重要,如果不加就会上面的报错
另外,
ssl.truststore.location里面配置的文件,如果是可以通过
ResourceUtils.getFile("classpath:aa.jks").getPath()
代替的,但要在pom文件里设置可以打包到class文件里
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<!-- 添加资源 -->
<resources>
<resource>
<directory>src/main/resources</directory>
<!-- src/main/resources下的指定资源放行 -->
<includes>
<include>**/*.properties</include>
<include>**/*.yml</include>
<include>**/*.xml</include>
<include>**/*.jks</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
完结撒花