kafka 示例(spring boot)顺序消息

论坛 期权论坛 脚本     
匿名技术用户   2021-1-3 19:44   32   0

springboot kafka 顺序消息

实现方式:将需要顺序消费的消息发送到同一个分区

*********************************************

使用示例

********************************

application.yml

spring:
  kafka:
    bootstrap-servers: 172.18.0.12:9092
    listener:
      missing-topics-fatal: false
      type: batch

********************************

producer 端

@Service
public class ProducerService {

    @Resource
    private KafkaTemplate<Object,String> kafkaTemplate;

    public void send() throws Exception {
        for (int i=0;i<100;i++){
            SendResult<Object,String> result=kafkaTemplate.send("order",0,null,"瓜田李下 顺序消息"+i).get();
            System.out.println("发送时间:"+System.currentTimeMillis()+"  "+result);
        }
    }
}

*************************************

consumer 端

@Component
public class ConsumerService {

    @KafkaListener(groupId = "consumerGroup",topics = "order")
    public void consumer(ConsumerRecords<Object,String> consumerRecords){
        for(TopicPartition topicPartition:consumerRecords.partitions()){
            for(ConsumerRecord<Object,String> consumerRecord:consumerRecords.records(topicPartition)){
                System.out.println("消费时间:"+System.currentTimeMillis()+" "+consumerRecord.value());
            }
        }
    }
}

******************************************

控制台输出

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP