1 资源

资源信息版本号备注
kafka2.12-2.1.0IP: 192.168.51.4
springboot2.1.5.RELEASE

springboot-kafka-demo 源码 下载

2 kafka安装

需要安装kafka,如果未安装,可参考博文:

MQ Kafka安装部署和配置

3 springboot整合

3.1 父pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.auskat.demo</groupId>
    <artifactId>springboot-kafka-demo</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>kafka-consumer</module>
        <module>kafka-producer</module>
    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>
    </dependencies>

</project>

3.2 生产者模块

3.2.1 application.yml

server.servlet.context-path=/producer
server.port=8001

## spring 整合 kafka
spring.kafka.bootstrap-servers=192.168.51.4:9092
## kafka producer 发送消息失败的一个重试次数
spring.kafka.producer.retries=0
## 批量发送数据的配置
spring.kafka.producer.batch-size=16384
## 设置kafka 生产者内存缓存区的大小(32)
spring.kafka.producer.buffer-memory=33554432
## kafka消息的序列化配置
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer

# acks=0 : 生产者在成功写入消息之前不会等待任何来自服务器的响应。
# acks=1 : 只要集群的首领节点收到消息,生产者就会收到一个来自服务器成功响应。
# acks=-1: 表示分区leader必须等待消息被成功写入到所有的ISR副本(同步副本)中才认为producer请求成功。这种方案提供最高的消息持久性保证,但是理论上吞吐率也是最差的。

## 	这个是kafka生产端最重要的选项
spring.kafka.producer.acks=1

3.2.2 配置类

package com.auskat.demo.kafka.config;

import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.KafkaAdmin;

import java.util.HashMap;
import java.util.Map;

/**
 * 类文件: KafkaInitialConfiguration
 * <p>
 * <p>
 * 类描述:
 * <p>
 * 作     者: AusKa_T
 * <p>
 * 日     期: 2021/3/25 0025
 * <p>
 * 时     间: 22:28
 * <p>
 */
@Configuration
public class KafkaInitialConfiguration {

    @Value("{spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Bean
    public KafkaAdmin kafkaAdmin() {
        Map<String, Object> props = new HashMap<>();
        //配置Kafka实例的连接地址
        props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        KafkaAdmin admin = new KafkaAdmin(props);
        return admin;
    }

    @Bean
    public AdminClient adminClient() {
        return AdminClient.create(kafkaAdmin().getConfig());
    }
}

3.2.3 自定义回调

package com.auskat.demo.kafka.callback;

import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * 类文件: CustomCallBack
 * <p>
 * <p>
 * 类描述:
 * <p>
 * 作     者: AusKa_T
 * <p>
 * 日     期: 2021/3/25 0025
 * <p>
 * 时     间: 21:20
 * <p>
 */
@Slf4j
public class CustomCallBack implements ListenableFutureCallback<SendResult<String, Object>> {


    /**
     * 发送成功
     * @param result 结果
     */
    @Override
    public void onSuccess(SendResult<String, Object> result) {
        assert result != null;
        log.info("发送消息成功: {}",result.toString());
    }

    /**
     * 发送失败
     * @param ex 异常信息
     */
    @Override
    public void onFailure(Throwable ex) {
        log.info("发送消息失败, 原因: {}",ex.getMessage());
    }

}

3.2.4 生产业务层

package com.auskat.demo.kafka.producer;

import com.auskat.demo.kafka.callback.CustomCallBack;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.Arrays;
import java.util.Collections;

/**
 * 类文件: KafkaProducerService
 * <p>
 * <p>
 * 类描述:
 * <p>
 * 作     者: AusKa_T
 * <p>
 * 日     期: 2021/3/25 0025
 * <p>
 * 时     间: 21:17
 * <p>
 */
@Slf4j
@Component
public class KafkaProducerService {

    @Autowired
    private KafkaTemplate<String,Object> kafkaTemplate;

    @Autowired
    private AdminClient adminClient;

    /**
     * 发送消息
     * @param topic 主题
     * @param object 数据
     */
    public void sendMessage(String topic, Object object) {
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topic, object);
        future.addCallback(new CustomCallBack());
    }

    /**
     * 创建 topic
     * @param topic topic名称
     */
    public void createTopic(String topic) {
        NewTopic newTopic = new NewTopic(topic, 2, (short) 1);
        adminClient.createTopics(Collections.singletonList(newTopic));
    }
}

3.3 消费者模块

3.3.1 application.yml

server.servlet.context-path=/consumer
server.port=8002

spring.kafka.bootstrap-servers=192.168.51.4:9092

## consumer 消息的签收机制:手工签收
spring.kafka.consumer.enable-auto-commit=false
spring.kafka.listener.ack-mode=manual
# 该属性指定了消费者在读取一个没有偏移量的分区或者偏移量无效的情况下该作何处理:
# latest(默认值)在偏移量无效的情况下,消费者将从最新的记录开始读取数据(在消费者启动之后生成的记录)
# earliest :在偏移量无效的情况下,消费者将从起始位置读取分区的记录
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.listener.concurrency=5

3.3.2 消费者业务层

package com.auskat.demo.kafka.consumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

/**
 * 类文件: KafkaConsumerService
 * <p>
 * <p>
 * 类描述:
 * <p>
 * 作     者: AusKa_T
 * <p>
 * 日     期: 2021/3/25 0025
 * <p>
 * 时     间: 22:00
 * <p>
 */
@Slf4j
@Component
public class KafkaConsumerService {

    @KafkaListener(groupId = "group02", topics = "topic02")
    public void onMessage(ConsumerRecord<String,Object> record, Acknowledgment acknowledgment){
        log.info("消费端接收到消息: {}", record.value());

        // 手工签收机制
        acknowledgment.acknowledge();
    }
}

4 功能测试

package com.auskat.demo.kafka;

import com.auskat.demo.kafka.producer.KafkaProducerService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 类文件: ApplicationTests
 * <p>
 * <p>
 * 类描述:
 * <p>
 * 作     者: AusKa_T
 * <p>
 * 日     期: 2021/3/25 0025
 * <p>
 * 时     间: 22:23
 * <p>
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @Autowired
    private KafkaProducerService kafkaProducerService;

    @Test
    public void send() throws InterruptedException {

        String topic = "topic02";
        for(int i=0; i < 1000; i ++) {
            kafkaProducerService.sendMessage(topic, "hello kafka" + i);
            Thread.sleep(5);
        }

        Thread.sleep(Integer.MAX_VALUE);

    }
}

5 相关信息

  • 博文不易,辛苦各位猿友点个关注和赞,感谢
Logo

Kafka开源项目指南提供详尽教程,助开发者掌握其架构、配置和使用,实现高效数据流管理和实时处理。它高性能、可扩展,适合日志收集和实时数据处理,通过持久化保障数据安全,是企业大数据生态系统的核心。

更多推荐