Spring Cloud Stream Kafka 特定分区的消息始终由特定的消费者实例消费

实验目的:Kafka特定分区的消息始终由消费者应用的特定实例消费,例如,分区1由实例索引0的实例消费,分区2由实例索引1的实例消费,分区3由实例索引2的实例消费。

项目介绍:项目分为1个生产者实例,3个消费者实例,生产者应用和消费者应用均为Spring Cloud Eureka客户端项目。生产者实例将消息发送到Kafka Topic的3个分区中,消费者的3个实例分别按实例索引消费Kafka Topic的3个分区数据。即,实例索引0的实例消费分区0,实例索引1的实例消费分区1,实例索引2的实例消费分区2。

生产者项目结构:

生产者项目结构

 

引入Spring Cloud Stream依赖

<dependency>

    <groupId>org.springframework.cloud</groupId>

    <artifactId>spring-cloud-stream-binder-kafka-streams</artifactId>

</dependency>



<dependency>

    <groupId>org.springframework.cloud</groupId>

    <artifactId>spring-cloud-stream-binder-kafka</artifactId>

</dependency>

 

应用类:
 

SpringCloudStreamKafkaProducerApplication.java

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.stream.annotation.EnableBinding;

import org.springframework.cloud.stream.messaging.Source;

import org.springframework.messaging.support.MessageBuilder;

import org.springframework.scheduling.annotation.EnableScheduling;

import org.springframework.scheduling.annotation.Scheduled;



@EnableBinding(Source.class)

@EnableScheduling

@SpringBootApplication

public class SpringCloudStreamKafkaProducerApplication {



    @Autowired

    private Source source;



    public static void main(String[] args) {

        SpringApplication.run(SpringCloudStreamKafkaProducerApplication.class, args);

    }



    @Scheduled(fixedRate = 5000)

    public void handle1() {

        Person person = new Person();



        Long currentTimeMillis = System.currentTimeMillis();



        person.setId(Long.parseLong(currentTimeMillis.toString().substring(currentTimeMillis.toString().length() - 1)));

        person.setName("rock ");



        System.out.println("send a person..." + person);



        source.output().send(MessageBuilder.withPayload(person).build());

    }



    public static class Person {

        private Long id;

        private String name;



        public Long getId() {

            return id;

        }



        pu
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值