dependencies {
compile group: 'org.apache.kafka', name: 'kafka-clients', version: '2.8.1'
}
예제는 간단!
kafka 설치한 서버에 어떠한 시스템이 메세지를 게시하면
그 해당 메세지를 구독하는 코드이다.
package kafkaConsumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import java.util.Collections;
import java.util.Properties;
/**
* Created by Karim
* Date : 2021-11-01
* Time : 오전 10:48
*/
public class KafkaConsumerBasis {
private static final String KAFKA_SINGLE_IP = "ServerIp:KafkaPort";
private static final String TOPIC_NAME = "karim-topic";
public static void main(String[] args) {
Properties props = new Properties();
// kafka server host 및 port 설정
props.put("bootstrap.servers", KAFKA_SINGLE_IP);
props.put("group.id", "karim-group-id-1"); // group-id 설정
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); // key deserializer
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); // value deserializer
// consumer 생성
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
// topic 설정
consumer.subscribe(Collections.singletonList(TOPIC_NAME));
try {
while (true) {
// 계속 loop를 돌면서 producer의 message를 띄운다.
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records)
System.out.println(record.value());
}
} catch (Exception e) {
} finally {
consumer.close();
}
}
}
[karim@kafka-single bin]$ ./kafka-console-producer.sh --broker-list localhost:9092 --topic karim-topic
> Karim velog cuteeeee-
[11:54:28.862],ConsumerConfig values:
allow.auto.create.topics = true
auto.commit.interval.ms = 5000
auto.offset.reset = latest
bootstrap.servers = [...:9092]
check.crcs = true
client.dns.lookup = use_all_dns_ips
client.id = consumer-karim-group-id-1-1
client.rack =
connections.max.idle.ms = 540000
default.api.timeout.ms = 60000
enable.auto.commit = true
exclude.internal.topics = true
fetch.max.bytes = 52428800
fetch.max.wait.ms = 500
fetch.min.bytes = 1
group.id = karim-group-id-1
group.instance.id = null
heartbeat.interval.ms = 3000
interceptor.classes = []
internal.leave.group.on.close = true
internal.throw.on.fetch.stable.offset.unsupported = false
isolation.level = read_uncommitted
key.deserializer = class org.apache.kafka.common.serialization.StringDeserializer
max.partition.fetch.bytes = 1048576
max.poll.interval.ms = 300000
max.poll.records = 500
metadata.max.age.ms = 300000
metric.reporters = []
metrics.num.samples = 2
metrics.recording.level = INFO
metrics.sample.window.ms = 30000
partition.assignment.strategy = [class org.apache.kafka.clients.consumer.RangeAssignor]
receive.buffer.bytes = 65536
reconnect.backoff.max.ms = 1000
reconnect.backoff.ms = 50
request.timeout.ms = 30000
retry.backoff.ms = 100
sasl.client.callback.handler.class = null
sasl.jaas.config = null
sasl.kerberos.kinit.cmd = /usr/bin/kinit
sasl.kerberos.min.time.before.relogin = 60000
sasl.kerberos.service.name = null
sasl.kerberos.ticket.renew.jitter = 0.05
sasl.kerberos.ticket.renew.window.factor = 0.8
sasl.login.callback.handler.class = null
sasl.login.class = null
sasl.login.refresh.buffer.seconds = 300
sasl.login.refresh.min.period.seconds = 60
sasl.login.refresh.window.factor = 0.8
sasl.login.refresh.window.jitter = 0.05
sasl.mechanism = GSSAPI
security.protocol = PLAINTEXT
security.providers = null
send.buffer.bytes = 131072
session.timeout.ms = 10000
socket.connection.setup.timeout.max.ms = 30000
socket.connection.setup.timeout.ms = 10000
ssl.cipher.suites = null
ssl.enabled.protocols = [TLSv1.2]
ssl.endpoint.identification.algorithm = https
ssl.engine.factory.class = null
ssl.key.password = null
ssl.keymanager.algorithm = SunX509
ssl.keystore.certificate.chain = null
ssl.keystore.key = null
ssl.keystore.location = null
ssl.keystore.password = null
ssl.keystore.type = JKS
ssl.protocol = TLSv1.2
ssl.provider = null
ssl.secure.random.implementation = null
ssl.trustmanager.algorithm = PKIX
ssl.truststore.certificates = null
ssl.truststore.location = null
ssl.truststore.password = null
ssl.truststore.type = JKS
value.deserializer = class org.apache.kafka.common.serialization.StringDeserializer
[11:54:29.530],Kafka version: 2.8.1
[11:54:29.532],Kafka commitId: 839b886f9b732b15
[11:54:29.532],Kafka startTimeMs: 1635735269527
[11:54:29.535],[Consumer clientId=consumer-karim-group-id-1-1, groupId=karim-group-id-1] Subscribed to topic(s): karim-topic
[11:54:29.989],[Consumer clientId=consumer-karim-group-id-1-1, groupId=karim-group-id-1] Cluster ID: ig7CcFmqSeCTqaj1ozuCEA
[11:54:29.991],[Consumer clientId=consumer-karim-group-id-1-1, groupId=karim-group-id-1] Discovered group coordinator 192.168.124.238:1146 (id: 2147483646 rack: null)
[11:54:29.994],[Consumer clientId=consumer-karim-group-id-1-1, groupId=karim-group-id-1] (Re-)joining group
[11:54:30.008],[Consumer clientId=consumer-karim-group-id-1-1, groupId=karim-group-id-1] (Re-)joining group
[11:54:33.013],[Consumer clientId=consumer-karim-group-id-1-1, groupId=karim-group-id-1] Successfully joined group with generation Generation{generationId=1, memberId='consumer-karim-group-id-1-1-c6cce5fa-5e99-4361-82e0-13bab637caab', protocol='range'}
[11:54:33.017],[Consumer clientId=consumer-karim-group-id-1-1, groupId=karim-group-id-1] Finished assignment for group at generation 1: {consumer-karim-group-id-1-1-c6cce5fa-5e99-4361-82e0-13bab637caab=Assignment(partitions=[karim-topic-0])}
[11:54:33.024],[Consumer clientId=consumer-karim-group-id-1-1, groupId=karim-group-id-1] Successfully synced group in generation Generation{generationId=1, memberId='consumer-karim-group-id-1-1-c6cce5fa-5e99-4361-82e0-13bab637caab', protocol='range'}
[11:54:33.025],[Consumer clientId=consumer-karim-group-id-1-1, groupId=karim-group-id-1] Notifying assignor about the new Assignment(partitions=[karim-topic-0])
[11:54:33.028],[Consumer clientId=consumer-karim-group-id-1-1, groupId=karim-group-id-1] Adding newly assigned partitions: karim-topic-0
[11:54:33.037],[Consumer clientId=consumer-karim-group-id-1-1, groupId=karim-group-id-1] Found no committed offset for partition karim-topic-0
[11:54:33.053],[Consumer clientId=consumer-karim-group-id-1-1, groupId=karim-group-id-1] Resetting offset for partition karim-topic-0 to position FetchPosition{offset=33, offsetEpoch=Optional.empty, currentLeader=LeaderAndEpoch{leader=Optional[192.168.124.238:1146 (id: 1 rack: null)], epoch=0}}.
Karim velog cuteeeee-