七、springboot集成kafka(简单使用)

一、下载安装kafka

官网地址:Apache Kafkahttps://kafka.apache.org/downloads,这里选择相对稳定的版本

或者是使用已经下载的,百度云盘下载一下:

链接:https://pan.baidu.com/s/16xOkCJCQ5NzHSjy5ZoqWrA?pwd=yc7g 
提取码:yc7g

解压:tar -zxvf kafka_2.13-2.5.0.tgz
解压后即完成了安装,不需要做其他操作;

修改解压后文件名并移动到指定目录:mv kafka_2.13-2.5.0 kafka
切换到kafka的目录:cd kafka/config

修改server.properties配置:

此处ip_kafka是kafka部署的ip公网,ip_zookeeper是zookeeper部署的ip公网


listeners=PLAINTEXT://ip_kafka:9092
advertised.listeners=PLAINTEXT://ip_kafka:9092


zookeeper.connect=ip_zookeeper:2181

启动kafka:

cd kafka/bin

./kafka-server-start.sh …/config/server.properties &

Kafka启动后默认端口:9092
查看kafka进程:

ps -ef | grep kafka 或者 jps

注:kafka启动需要先启动zookeeper;
关闭kafka:

cd kafka/bin

./kafka-server-stop.sh …/config/server.properties

二、SpringBoot整合Kafka
1:我们基于SpringBoot来快速入门Kafka,我这里使用的SpringBoot版本是2.6.0,具体依赖如下:


<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.0</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.kafka</groupId>
        <artifactId>spring-kafka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.69</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

2:导入依赖之后需要为SpringBoot创建启动类,在启动类中我们通过注解的方式创建一个Topic,如下

@SpringBootApplication
public class KafkaApplication {
    public static void main(String[] args) {
        SpringApplication.run(KafkaApplication.class, args);
    }
}

3:因为是基于SpringBoot开发,所以需要在properties对kafka做一些常规配置,如下:

server.port=8080
spring.application.name=application-kafka

#这个是kafka的地址,对应你server.properties中配置的kafka服务器的链接地址
spring.kafka.bootstrap-servers=ip_kafka:9092
#主题
spring.kafka.template.default-topic=test
#对生产者的配置
spring.kafka.producer.client-id=MyProducer
#序列化
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
# 消息发送重试次数
spring.kafka.producer.retries=1
#生产者发送消息到Kafka的应答模式级别:多少个分区副本备份完成时向生产者发送ack确认(可选0、1、all/-1)
#acks = 0:设置成 表示 producer 完全不理睬 leader broker 端的处理结果。此时producer 发送消息后立即开启下 条消息的发送,根本不等待 leader broker 端返回结果
#acks= all 或者-1 :表示当发送消息时, leader broker 不仅会将消息写入本地日志,同时还会等待所有其他副本都成功写入它们各自的本地日志后,才发送响应结果给,消息安全但是吞吐量会比较低。
#acks = 1:默认的参数值。 producer 发送消息后 leader broker仅将该消息写入本地日志,然后便发送响应结果给producer,而无须等待其他副本写入该消息。折中方案,只要leader一直活着消息就不会丢失,同时也保证了吞吐量
spring.kafka.producer.acks=1
#批量大小
spring.kafka.producer.batch-size=16384
#提交延迟
spring.kafka.producer.properties.linger.spring.kafka.ms=0


spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
#消费者的ID,这个对应 config/consumer.properties中的group.id
spring.kafka.consumer.group-id=test-consumer-group

spring.kafka.consumer.enable-auto-commit=true
spring.kafka.consumer.auto-commit-interval=100


4:生产者发送消息
编写生产者案例 ,Kafka提供了 KafkaTemplate 用来向Kafka发送消息,直接在查询中注入即可使用。KafkaTemplate提供了很多个重载的send方法,方法返回ListenableFuture对象,即发送的结果对象。下面我编写了一个controller作为生产者

@RestController
public class HelloProducer {
    private static Logger logger = LoggerFactory.getLogger(HelloProducer.class);
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Value("${spring.kafka.template.default-topic}")
    private String topic;

    //同步阻塞:需要特别注意的是: future.get()方法会阻塞,他会一直尝试获取发送结果,如果Kafka迟迟没有返回发送结果那么程序会阻塞到这里。所以这种发送方式是同步的。
    //当然如果你的消息不重要允许丢失你也可以直接执行 : kafkaTemplate.send ,不调用get()方法获取发送结果,程序就不会阻塞,当然你也就不知道消息到底有没有发送成功。
    @GetMapping("/send/{msg}")
    public String sendMsg(@PathVariable("msg")String msg) throws ExecutionException, InterruptedException {

        ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(KafkaApplication.TOPIC_NAME, msg);
        System.out.println("发送结果:"+future.get().toString());
        return "发送成功";
    }


    //异步非阻塞
    @GetMapping("/send/syn/{msg}")
    public String sendMsgSyn(@PathVariable("msg")String msg) throws ExecutionException, InterruptedException {

        ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(topic, msg);

        future.addCallback(new ListenableFutureCallback(){

            @Override
            public void onSuccess(Object result) {
                System.out.println("发送成功 result = "+result);
            }

            @Override
            public void onFailure(Throwable ex) {
                System.out.println("发送异常");
                ex.printStackTrace();
            }
        });
        return "发送成功";
    }
}


5:生产者监听器

Kafka提供了ProducerListener 监听器来异步监听生产者消息是否发送成功,我们可以自定义一个kafkaTemplate添加ProducerListener,当消息发送失败我们可以拿到消息进行重试或者把失败消息记录到数据库定时重试。

@Configuration
public class KafkaConfig{
    //生产者工厂
    @Autowired
    ProducerFactory producerFactory;
    @Bean
    public KafkaTemplate<String,String> kafkaTemplate(){

        KafkaTemplate<String, String> kafkaTemplate = new KafkaTemplate<String, String>(producerFactory);
        //生产者监听器
        kafkaTemplate.setProducerListener(new ProducerListener<String, String>() {
            @Override
            public void onSuccess(ProducerRecord<String, String> producerRecord, RecordMetadata recordMetadata) {
                ProducerListener.super.onSuccess(producerRecord, recordMetadata);
                System.out.println("发送成功 "+producerRecord.toString());
            }

            @Override
            public void onError(ProducerRecord<String, String> producerRecord, RecordMetadata recordMetadata, Exception exception) {
                ProducerListener.super.onError(producerRecord, recordMetadata, exception);
                System.out.println("发送失败producerRecord="+producerRecord.toString());
                System.out.println("发送失败recordMetadata="+recordMetadata.toString());
                System.out.println(exception.getMessage());
            }

    });
        return kafkaTemplate;
    }
}

当我们发送一条消息,既会走 ListenableFutureCallback 回调,也会走ProducerListener回调。执行测试方法,查看控制台效果:

发送成功 result = SendResult [producerRecord=ProducerRecord(topic=test, partition=null, headers=RecordHeaders(headers = [], isReadOnly = true), key=null, value={你好}, timestamp=null), recordMetadata=test-0@5]


发送成功 ProducerRecord(topic=test, partition=null, headers=RecordHeaders(headers = [], isReadOnly = true), key=null, value={你好}, timestamp=null)


6:消费者接收消息
我们可以通过定义一个 KafkaMessageListenerContainer 的Bean,为他添加 MessageListener 来消费消息,但是这种很麻烦,具体用法可以看 SpringBoot文档 ,Kafka另外提供了 @KafkaListener注释来接收消息,用法比较简单,我们演示注解方式如下:

@Component
public class HelloConsumer {

    private static Logger logger = LoggerFactory.getLogger(HelloConsumer.class);

    //监听一个或者多个Topic
    @KafkaListener(topics = "${spring.kafka.template.default-topic}")
    public void listener (ConsumerRecord<String, String> record) {
        //JDK8的一个类,Optional
        Optional<?> kafkaMessage = Optional.ofNullable(record.value());
        if (kafkaMessage.isPresent()) {
            Object message = kafkaMessage.get();
            logger.info("接收到的消息:" + message);
            System.out.println("收到消息:"+message);
        }

        

     /**

         * headers:消息头信息

         * offset:此记录在相应的 Kafka 分区中的位置。

         * partition:记录所在的分区

         * serializedKeySize:序列化的未压缩密钥的大小(以字节为单位),如果 key为 null,则返回的大小为 -1

         * serializedValueSize:序列化的未压缩值(消息正文)的大小(以字节为单位,record.value().getBytes().length)。如果值为 null,则返回的大小为 -1

         * timestamp:记录的时间戳

         * TimestampType:记录的时间戳类型

         * topic:接收此记录的主题

         * value:消息内容

         */

        Headers headers = record.headers();

        long offset = record.offset();

        int partition = record.partition();

        int serializedKeySize = record.serializedKeySize();

        int serializedValueSize = record.serializedValueSize();

        long timestamp = record.timestamp();

        TimestampType timestampType = record.timestampType();

        String topic = record.topic();

        Object value = record.value();

        System.out.println("收到消息:");

        System.out.println("\theaders=" + headers);

        System.out.println("\toffset=" + offset);

        System.out.println("\tpartition=" + partition);

        System.out.println("\tserializedKeySize=" + serializedKeySize);

        System.out.println("\tserializedValueSize=" + serializedValueSize);

        System.out.println("\ttimestamp=" + timestamp);

        System.out.println("\ttimestampType=" + timestampType);

        System.out.println("\ttopic=" + topic);

        System.out.println("\tvalue=" + value);

    }
}

执行测试方法,查看控制台效果:

2023-12-27 17:15:18.747  INFO 23696 --- [ntainer#0-0-C-1] c.e.freemarker.controller.HelloConsumer  : 接收到的消息:{你好}
收到消息:{你好}
收到消息:
    headers=RecordHeaders(headers = [], isReadOnly = false)
    offset=6
    partition=0
    serializedKeySize=-1
    serializedValueSize=8
    timestamp=1703668518677
    timestampType=CreateTime
    topic=test
    value={你好}

  • 22
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot集成Kafka可以使用Spring Kafka库来实现。以下是步骤: 1. 添加Spring Kafka依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> <version>2.3.7.RELEASE</version> </dependency> ``` 2. 配置Kafka 在application.properties文件中添加以下配置: ```properties spring.kafka.bootstrap-servers=<kafka服务器地址> spring.kafka.consumer.group-id=<消费者组ID> ``` 3. 创建Kafka生产者 使用KafkaTemplate类创建生产者。以下是一个示例: ```java @Service public class MyKafkaProducer { @Autowired private KafkaTemplate<String, String> kafkaTemplate; public void sendMessage(String topic, String message) { kafkaTemplate.send(topic, message); } } ``` 4. 创建Kafka消费者 使用@KafkaListener注解创建消费者。以下是一个示例: ```java @Service public class MyKafkaConsumer { @KafkaListener(topics = "<要消费的主题>") public void consume(String message) { // 处理消息 } } ``` 5. 发送和接收消息 使用上面创建的Kafka生产者发送消息,使用上面创建的Kafka消费者接收消息。 以上就是Spring Boot集成Kafka的基本步骤。需要注意的是,Kafka的具体使用方式和配置可能因版本而异,需要根据实际情况进行调整。 ### 回答2: Spring Boot 是一个用于简化 Spring 应用程序开发的框架,它提供了很多便捷的功能和配置,使得我们可以更容易地集成使用 Kafka 。 首先,我们需要在 pom.xml 文件中添加 Kafka 的依赖: ```xml <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency> ``` 然后,我们需要在 application.properties(或 application.yml)文件中配置 Kafka 的连接地址和其他相关属性: ```properties spring.kafka.bootstrap-servers=your-kafka-server-address spring.kafka.consumer.group-id=your-consumer-group-id spring.kafka.consumer.auto-offset-reset=earliest spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer ``` 在代码中,我们可以使用 KafkaTemplate 类来发送消息到 Kafka 或接收 Kafka 的消息。我们可以通过注入 KafkaTemplate 对象来使用它。 例如,我们可以定义一个 Producer 类来发送消息: ```java @Service public class KafkaProducer { @Autowired private KafkaTemplate<String, String> kafkaTemplate; public void sendMessage(String topic, String message) { kafkaTemplate.send(topic, message); } } ``` 我们还可以定义一个 Consumer 类来接收消息: ```java @Service public class KafkaConsumer { @KafkaListener(topics = "your-topic-name") public void receiveMessage(String message) { System.out.println("Received message: " + message); } } ``` 在这个例子中,我们通过使用 @KafkaListener 注解来指定要监听的主题,并在 receiveMessage 方法中处理接收到的消息。 通过以上步骤,我们就可以在 Spring Boot 中集成使用 Kafka 了。我们可以使用 KafkaTemplate 发送消息,使用 @KafkaListener 注解来监听和处理消息。同时,我们还可以根据自己的需求配置更多的 Kafka 相关属性,例如设置消费者组、反序列化器等。 总之,Spring Boot 集成 Kafka 的过程主要步骤包括添加依赖、配置 Kafka 连接、编写 Producer 和 Consumer 类,通过 KafkaTemplate 发送消息,使用 @KafkaListener 注解监听并处理消息。以上就是关于如何在 Spring Boot 中集成 Kafka 的简要介绍。 ### 回答3: Spring Boot提供了对Kafka集成支持,使得使用Kafka进行消息传递变得简单和高效。下面是使用Spring Boot集成Kafka的步骤: 1. 配置Kafka依赖:在pom.xml文件中添加Kafka的依赖项。 ``` <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency> ``` 2. 配置Kafka相关属性:在application.properties文件中配置Kafka的相关属性,包括Kafka服务器地址、端口号等。 ``` spring.kafka.bootstrap-servers=localhost:9092 ``` 3. 创建Kafka生产者:使用Spring Kafka提供的KafkaTemplate类来创建一个Kafka生产者,用于发送消息到Kafka。 ```java @Autowired private KafkaTemplate<String, String> kafkaTemplate; public void sendMessage(String topic, String message) { kafkaTemplate.send(topic, message); } ``` 4. 创建Kafka消费者:使用@KafkaListener注解来创建Kafka消费者,监听指定的主题,并处理接收到的消息。 ```java @KafkaListener(topics = "myTopic") public void receiveMessage(String message) { System.out.println("Received message: " + message); // 进行消息处理 } ``` 5. 启动Kafka消费者:在Spring Boot应用程序的入口类上添加@EnableKafka注解,以启用Kafka消费者。 ```java @SpringBootApplication @EnableKafka public class SpringBootKafkaApplication { public static void main(String[] args) { SpringApplication.run(SpringBootKafkaApplication.class, args); } } ``` 通过以上步骤,我们就可以在Spring Boot中集成Kafka,并使用Kafka进行消息传递了。可以根据实际需求,进行消息的发送和接收处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值