Java客户端访问Kafka
    引入maven依赖

    1. <dependency>
    2. <groupId>org.apache.kafka</groupId>
    3. <artifactId>kafka-clients</artifactId>
    4. <version>2.4.1</version>
    5. </dependency>

    消息发送端代码

    1. package com.tuling.kafka.kafkaDemo;
    2. import com.alibaba.fastjson.JSON;
    3. import org.apache.kafka.clients.producer.*;
    4. import org.apache.kafka.common.serialization.StringSerializer;
    5. import java.util.Properties;
    6. import java.util.concurrent.CountDownLatch;
    7. import java.util.concurrent.ExecutionException;
    8. import java.util.concurrent.TimeUnit;
    9. public class MsgProducer {
    10. private final static String TOPIC_NAME = "my-replicated-topic";
    11. public static void main(String[] args) throws InterruptedException, ExecutionException {
    12. Properties props = new Properties();
    13. props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.65.60:9092,192.168.65.60:9093,192.168.65.60:9094");
    14. /*
    15. 发出消息持久化机制参数
    16. (1)acks=0: 表示producer不需要等待任何broker确认收到消息的回复,就可以继续发送下一条消息。性能最高,但是最容易丢消息。
    17. (2)acks=1: 至少要等待leader已经成功将数据写入本地log,但是不需要等待所有follower是否成功写入。就可以继续发送下一
    18. 条消息。这种情况下,如果follower没有成功备份数据,而此时leader又挂掉,则消息会丢失。
    19. (3)acks=-1或all: 需要等待 min.insync.replicas(默认为1,推荐配置大于等于2) 这个参数配置的副本个数都成功写入日志,这种策略会保证
    20. 只要有一个备份存活就不会丢失数据。这是最强的数据保证。一般除非是金融级别,或跟钱打交道的场景才会使用这种配置。
    21. */
    22. /*props.put(ProducerConfig.ACKS_CONFIG, "1");
    23. *//*
    24. 发送失败会重试,默认重试间隔100ms,重试能保证消息发送的可靠性,但是也可能造成消息重复发送,比如网络抖动,所以需要在
    25. 接收者那边做好消息接收的幂等性处理
    26. *//*
    27. props.put(ProducerConfig.RETRIES_CONFIG, 3);
    28. //重试间隔设置
    29. props.put(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, 300);
    30. //设置发送消息的本地缓冲区,如果设置了该缓冲区,消息会先发送到本地缓冲区,可以提高消息发送性能,默认值是33554432,即32MB
    31. props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
    32. *//*
    33. kafka本地线程会从缓冲区取数据,批量发送到broker,
    34. 设置批量发送消息的大小,默认值是16384,即16kb,就是说一个batch满了16kb就发送出去
    35. *//*
    36. props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
    37. *//*
    38. 默认值是0,意思就是消息必须立即被发送,但这样会影响性能
    39. 一般设置10毫秒左右,就是说这个消息发送完后会进入本地的一个batch,如果10毫秒内,这个batch满了16kb就会随batch一起被发送出去
    40. 如果10毫秒内,batch没满,那么也必须把消息发送出去,不能让消息的发送延迟时间太长
    41. *//*
    42. props.put(ProducerConfig.LINGER_MS_CONFIG, 10);*/
    43. //把发送的key从字符串序列化为字节数组
    44. props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
    45. //把发送消息value从字符串序列化为字节数组
    46. props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
    47. Producer<String, String> producer = new KafkaProducer<String, String>(props);
    48. int msgNum = 5;
    49. final CountDownLatch countDownLatch = new CountDownLatch(msgNum);
    50. for (int i = 1; i <= msgNum; i++) {
    51. Order order = new Order(i, 100 + i, 1, 1000.00);
    52. //指定发送分区
    53. /*ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>(TOPIC_NAME
    54. , 0, order.getOrderId().toString(), JSON.toJSONString(order));*/
    55. //未指定发送分区,具体发送的分区计算公式:hash(key)%partitionNum
    56. ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>(TOPIC_NAME
    57. , order.getOrderId().toString(), JSON.toJSONString(order));
    58. //等待消息发送成功的同步阻塞方法
    59. /*RecordMetadata metadata = producer.send(producerRecord).get();
    60. System.out.println("同步方式发送消息结果:" + "topic-" + metadata.topic() + "|partition-"
    61. + metadata.partition() + "|offset-" + metadata.offset());*/
    62. //异步回调方式发送消息
    63. producer.send(producerRecord, new Callback() {
    64. public void onCompletion(RecordMetadata metadata, Exception exception) {
    65. if (exception != null) {
    66. System.err.println("发送消息失败:" + exception.getStackTrace());
    67. }
    68. if (metadata != null) {
    69. System.out.println("异步方式发送消息结果:" + "topic-" + metadata.topic() + "|partition-"
    70. + metadata.partition() + "|offset-" + metadata.offset());
    71. }
    72. countDownLatch.countDown();
    73. }
    74. });
    75. //送积分 TODO
    76. }
    77. countDownLatch.await(5, TimeUnit.SECONDS);
    78. producer.close();
    79. }
    80. }

    消息接收端代码

    1. package com.tuling.kafka.kafkaDemo;
    2. import org.apache.kafka.clients.consumer.ConsumerConfig;
    3. import org.apache.kafka.clients.consumer.ConsumerRecord;
    4. import org.apache.kafka.clients.consumer.ConsumerRecords;
    5. import org.apache.kafka.clients.consumer.KafkaConsumer;
    6. import org.apache.kafka.common.serialization.StringDeserializer;
    7. import java.time.Duration;
    8. import java.util.Arrays;
    9. import java.util.Properties;
    10. public class MsgConsumer {
    11. private final static String TOPIC_NAME = "my-replicated-topic";
    12. private final static String CONSUMER_GROUP_NAME = "testGroup";
    13. public static void main(String[] args) {
    14. Properties props = new Properties();
    15. props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.65.60:9092,192.168.65.60:9093,192.168.65.60:9094");
    16. // 消费分组名
    17. props.put(ConsumerConfig.GROUP_ID_CONFIG, CONSUMER_GROUP_NAME);
    18. // 是否自动提交offset,默认就是true
    19. props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
    20. // 自动提交offset的间隔时间
    21. props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
    22. //props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
    23. /*
    24. 当消费主题的是一个新的消费组,或者指定offset的消费方式,offset不存在,那么应该如何消费
    25. latest(默认) :只消费自己启动之后发送到主题的消息
    26. earliest:第一次从头开始消费,以后按照消费offset记录继续消费,这个需要区别于consumer.seekToBeginning(每次都从头开始消费)
    27. */
    28. //props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
    29. /*
    30. consumer给broker发送心跳的间隔时间,broker接收到心跳如果此时有rebalance发生会通过心跳响应将
    31. rebalance方案下发给consumer,这个时间可以稍微短一点
    32. */
    33. props.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, 1000);
    34. /*
    35. 服务端broker多久感知不到一个consumer心跳就认为他故障了,会将其踢出消费组,
    36. 对应的Partition也会被重新分配给其他consumer,默认是10秒
    37. */
    38. props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 10 * 1000);
    39. //一次poll最大拉取消息的条数,如果消费者处理速度很快,可以设置大点,如果处理速度一般,可以设置小点
    40. props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 500);
    41. /*
    42. 如果两次poll操作间隔超过了这个时间,broker就会认为这个consumer处理能力太弱,
    43. 会将其踢出消费组,将分区分配给别的consumer消费
    44. */
    45. props.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 30 * 1000);
    46. props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    47. props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    48. KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
    49. consumer.subscribe(Arrays.asList(TOPIC_NAME));
    50. // 消费指定分区
    51. //consumer.assign(Arrays.asList(new TopicPartition(TOPIC_NAME, 0)));
    52. //消息回溯消费
    53. /*consumer.assign(Arrays.asList(new TopicPartition(TOPIC_NAME, 0)));
    54. consumer.seekToBeginning(Arrays.asList(new TopicPartition(TOPIC_NAME, 0)));*/
    55. //指定offset消费
    56. /*consumer.assign(Arrays.asList(new TopicPartition(TOPIC_NAME, 0)));
    57. consumer.seek(new TopicPartition(TOPIC_NAME, 0), 10);*/
    58. //从指定时间点开始消费
    59. /*List<PartitionInfo> topicPartitions = consumer.partitionsFor(TOPIC_NAME);
    60. //从1小时前开始消费
    61. long fetchDataTime = new Date().getTime() - 1000 * 60 * 60;
    62. Map<TopicPartition, Long> map = new HashMap<>();
    63. for (PartitionInfo par : topicPartitions) {
    64. map.put(new TopicPartition(topicName, par.partition()), fetchDataTime);
    65. }
    66. Map<TopicPartition, OffsetAndTimestamp> parMap = consumer.offsetsForTimes(map);
    67. for (Map.Entry<TopicPartition, OffsetAndTimestamp> entry : parMap.entrySet()) {
    68. TopicPartition key = entry.getKey();
    69. OffsetAndTimestamp value = entry.getValue();
    70. if (key == null || value == null) continue;
    71. Long offset = value.offset();
    72. System.out.println("partition-" + key.partition() + "|offset-" + offset);
    73. System.out.println();
    74. //根据消费里的timestamp确定offset
    75. if (value != null) {
    76. consumer.assign(Arrays.asList(key));
    77. consumer.seek(key, offset);
    78. }
    79. }*/
    80. while (true) {
    81. /*
    82. * poll() API 是拉取消息的长轮询
    83. */
    84. ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
    85. for (ConsumerRecord<String, String> record : records) {
    86. System.out.printf("收到消息:partition = %d,offset = %d, key = %s, value = %s%n", record.partition(),
    87. record.offset(), record.key(), record.value());
    88. }
    89. /*if (records.count() > 0) {
    90. // 手动同步提交offset,当前线程会阻塞直到offset提交成功
    91. // 一般使用同步提交,因为提交之后一般也没有什么逻辑代码了
    92. consumer.commitSync();
    93. // 手动异步提交offset,当前线程提交offset不会阻塞,可以继续处理后面的程序逻辑
    94. consumer.commitAsync(new OffsetCommitCallback() {
    95. @Override
    96. public void onComplete(Map<TopicPartition, OffsetAndMetadata> offsets, Exception exception) {
    97. if (exception != null) {
    98. System.err.println("Commit failed for " + offsets);
    99. System.err.println("Commit failed exception: " + exception.getStackTrace());
    100. }
    101. }
    102. });
    103. }*/
    104. }
    105. }
    106. }

    Spring Boot整合Kafka
    引入spring boot kafka依赖,详见项目实例:spring-boot-kafka

    1. <dependency>
    2. <groupId>org.springframework.kafka</groupId>
    3. <artifactId>spring-kafka</artifactId>
    4. </dependency>

    application.yml配置如下:

    1. server:
    2. port: 8080
    3. spring:
    4. kafka:
    5. bootstrap-servers: 192.168.65.60:9092,192.168.65.60:9093,192.168.65.60:9094
    6. producer: # 生产者
    7. retries: 3 # 设置大于0的值,则客户端会将发送失败的记录重新发送
    8. batch-size: 16384
    9. buffer-memory: 33554432
    10. acks: 1
    11. # 指定消息key和消息体的编解码方式
    12. key-serializer: org.apache.kafka.common.serialization.StringSerializer
    13. value-serializer: org.apache.kafka.common.serialization.StringSerializer
    14. consumer:
    15. group-id: default-group
    16. enable-auto-commit: false
    17. auto-offset-reset: earliest
    18. key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
    19. value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
    20. listener:
    21. # 当每一条记录被消费者监听器(ListenerConsumer)处理之后提交
    22. # RECORD
    23. # 当每一批poll()的数据被消费者监听器(ListenerConsumer)处理之后提交
    24. # BATCH
    25. # 当每一批poll()的数据被消费者监听器(ListenerConsumer)处理之后,距离上次提交时间大于TIME时提交
    26. # TIME
    27. # 当每一批poll()的数据被消费者监听器(ListenerConsumer)处理之后,被处理record数量大于等于COUNT时提交
    28. # COUNT
    29. # TIME | COUNT 有一个条件满足时提交
    30. # COUNT_TIME
    31. # 当每一批poll()的数据被消费者监听器(ListenerConsumer)处理之后, 手动调用Acknowledgment.acknowledge()后提交
    32. # MANUAL
    33. # 手动调用Acknowledgment.acknowledge()后立即提交,一般使用这种
    34. # MANUAL_IMMEDIATE
    35. ack-mode: manual_immediate

    发送者代码:

    1. package com.kafka;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. import org.springframework.kafka.core.KafkaTemplate;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import org.springframework.web.bind.annotation.RestController;
    6. @RestController
    7. public class KafkaController {
    8. private final static String TOPIC_NAME = "my-replicated-topic";
    9. @Autowired
    10. private KafkaTemplate<String, String> kafkaTemplate;
    11. @RequestMapping("/send")
    12. public void send() {
    13. kafkaTemplate.send(TOPIC_NAME, 0, "key", "this is a msg");
    14. }
    15. }

    消费者代码:

    1. package com.kafka;
    2. import org.apache.kafka.clients.consumer.ConsumerRecord;
    3. import org.springframework.kafka.annotation.KafkaListener;
    4. import org.springframework.kafka.support.Acknowledgment;
    5. import org.springframework.stereotype.Component;
    6. @Component
    7. public class MyConsumer {
    8. /**
    9. * @KafkaListener(groupId = "testGroup", topicPartitions = {
    10. * @TopicPartition(topic = "topic1", partitions = {"0", "1"}),
    11. * @TopicPartition(topic = "topic2", partitions = "0",
    12. * partitionOffsets = @PartitionOffset(partition = "1", initialOffset = "100"))
    13. * },concurrency = "6")
    14. * //concurrency就是同组下的消费者个数,就是并发消费数,必须小于等于分区总数
    15. * @param record
    16. */
    17. @KafkaListener(topics = "my-replicated-topic",groupId = "zhugeGroup")
    18. public void listenZhugeGroup(ConsumerRecord<String, String> record, Acknowledgment ack) {
    19. String value = record.value();
    20. System.out.println(value);
    21. System.out.println(record);
    22. //手动提交offset
    23. ack.acknowledge();
    24. }
    25. /*//配置多个消费组
    26. @KafkaListener(topics = "my-replicated-topic",groupId = "tulingGroup")
    27. public void listenTulingGroup(ConsumerRecord<String, String> record, Acknowledgment ack) {
    28. String value = record.value();
    29. System.out.println(value);
    30. System.out.println(record);
    31. ack.acknowledge();
    32. }*/
    33. }