springboot集成kafka实战项目,kafka生产者、消费者、创建topic,指定消费分区

2023-11-18

springboot集成kafka实战项目,kafka生产者、消费者、创建topic,指定消费分区

前言

本项目代码可直接集成到你现有的springboot项目中。功能包括:
1.kafka生产者配置。
2.kafka消费者配置。(指定分区消费)
3.kafka topic配置。

工具:

1.windows环境下kafka_2.12-2.8.0。
2.offsetexplorer.exe kafkaTools工具(查看kafka数据)。
3.idea 开发工具。
4.springboot。

windows环境下kafka启动配置

  1. 配置文件

需要修改zookeeper.properties 和server.properties。
修改ip为本机ip(启动远程访问)
修改logs文件目录
在这里插入图片描述
zookeeper.properties配置

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
# 
#    http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# the directory where the snapshot is stored.
dataDir=/kafkadata
# the port at which the clients will connect
clientPort=2181
# disable the per-ip limit on the number of connections since this is a non-production config
maxClientCnxns=0
# Disable the adminserver by default to avoid port conflicts.
# Set the port to something non-conflicting if choosing to enable this
admin.enableServer=false
# admin.serverPort=8080

server.properties文件配置

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# see kafka.server.KafkaConfig for additional details and defaults

############################# Server Basics #############################

# The id of the broker. This must be set to a unique integer for each broker.
broker.id=0

############################# Socket Server Settings #############################

# The address the socket server listens on. It will get the value returned from 
# java.net.InetAddress.getCanonicalHostName() if not configured.
#   FORMAT:
#     listeners = listener_name://host_name:port
#   EXAMPLE:
#     listeners = PLAINTEXT://your.host.name:9092
listeners=PLAINTEXT://10.4.127.171:9092

# Hostname and port the broker will advertise to producers and consumers. If not set, 
# it uses the value for "listeners" if configured.  Otherwise, it will use the value
# returned from java.net.InetAddress.getCanonicalHostName().
advertised.listeners=PLAINTEXT://10.4.127.171:9092

# Maps listener names to security protocols, the default is for them to be the same. See the config documentation for more details
#listener.security.protocol.map=PLAINTEXT:PLAINTEXT,SSL:SSL,SASL_PLAINTEXT:SASL_PLAINTEXT,SASL_SSL:SASL_SSL

# The number of threads that the server uses for receiving requests from the network and sending responses to the network
num.network.threads=3

# The number of threads that the server uses for processing requests, which may include disk I/O
num.io.threads=8

# The send buffer (SO_SNDBUF) used by the socket server
socket.send.buffer.bytes=102400

# The receive buffer (SO_RCVBUF) used by the socket server
socket.receive.buffer.bytes=102400

# The maximum size of a request that the socket server will accept (protection against OOM)
socket.request.max.bytes=104857600


############################# Log Basics #############################

# A comma separated list of directories under which to store log files
log.dirs=/logs

# The default number of log partitions per topic. More partitions allow greater
# parallelism for consumption, but this will also result in more files across
# the brokers.
num.partitions=1

# The number of threads per data directory to be used for log recovery at startup and flushing at shutdown.
# This value is recommended to be increased for installations with data dirs located in RAID array.
num.recovery.threads.per.data.dir=1

############################# Internal Topic Settings  #############################
# The replication factor for the group metadata internal topics "__consumer_offsets" and "__transaction_state"
# For anything other than development testing, a value greater than 1 is recommended to ensure availability such as 3.
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1

############################# Log Flush Policy #############################

# Messages are immediately written to the filesystem but by default we only fsync() to sync
# the OS cache lazily. The following configurations control the flush of data to disk.
# There are a few important trade-offs here:
#    1. Durability: Unflushed data may be lost if you are not using replication.
#    2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush.
#    3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to excessive seeks.
# The settings below allow one to configure the flush policy to flush data after a period of time or
# every N messages (or both). This can be done globally and overridden on a per-topic basis.

# The number of messages to accept before forcing a flush of data to disk
#log.flush.interval.messages=10000

# The maximum amount of time a message can sit in a log before we force a flush
#log.flush.interval.ms=1000

############################# Log Retention Policy #############################

# The following configurations control the disposal of log segments. The policy can
# be set to delete segments after a period of time, or after a given size has accumulated.
# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens
# from the end of the log.

# The minimum age of a log file to be eligible for deletion due to age
log.retention.hours=168

# A size-based retention policy for logs. Segments are pruned from the log unless the remaining
# segments drop below log.retention.bytes. Functions independently of log.retention.hours.
#log.retention.bytes=1073741824

# The maximum size of a log segment file. When this size is reached a new log segment will be created.
log.segment.bytes=1073741824

# The interval at which log segments are checked to see if they can be deleted according
# to the retention policies
log.retention.check.interval.ms=300000

############################# Zookeeper #############################

# Zookeeper connection string (see zookeeper docs for details).
# This is a comma separated host:port pairs, each corresponding to a zk
# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002".
# You can also append an optional chroot string to the urls to specify the
# root directory for all kafka znodes.
zookeeper.connect=localhost:2181

# Timeout in ms for connecting to zookeeper
zookeeper.connection.timeout.ms=18000


############################# Group Coordinator Settings #############################

# The following configuration specifies the time, in milliseconds, that the GroupCoordinator will delay the initial consumer rebalance.
# The rebalance will be further delayed by the value of group.initial.rebalance.delay.ms as new members join the group, up to a maximum of max.poll.interval.ms.
# The default value for this is 3 seconds.
# We override this to 0 here as it makes for a better out-of-the-box experience for development and testing.
# However, in production environments the default value of 3 seconds is more suitable as this will help to avoid unnecessary, and potentially expensive, rebalances during application startup.
group.initial.rebalance.delay.ms=0

  1. 启动zookeeper
    在kafka_2.12-2.8.0目录下输入命令
.\bin\windows\zookeeper-server-start.bat  .\config\zookeeper.properties

启动zookeeper

在这里插入图片描述
3. 启动kafka
在kafka_2.12-2.8.0目录下输入命令

 .\bin\windows\kafka-server-start.bat  .\config\server.properties

在这里插入图片描述

代码实现

springboot项目的创建不再赘述。
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>dume</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>dume-springboot-kafka-server</name>
    <description>dume-springboot-kafka-server</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <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.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.49</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.yml文件配置

server:
  port: 8186
  servlet:
    context-path: /dume
    session:
      timeout: 30m #30分钟,测试的话时间不能太短,否
kafkaserver:
  server: 10.4.127.171:9092
  topic: dume-topic
  parttition: 0
  group-id: dume

3.topic配置

package com.example.dume.config;

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;

/**
 * @author dume
 * @create 2021-09-24 10:02
 **/
@Configuration
public class KafkaTopicConfig {
    @Value("${kafkaserver.server}")
    private String boardServer;
    @Value("${kafkaserver.topic}")
    private String topic;
    /**
     * 定义一个KafkaAdmin的bean,可以自动检测集群中是否存在topic,不存在则创建
     */
    @Bean
    public KafkaAdmin kafkaAdmin() {
        Map<String, Object> configs = new HashMap<>();
        // 指定多个kafka集群多个地址,例如:192.168.2.11,9092,192.168.2.12:9092,192.168.2.13:9092
        configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, boardServer);
        return new KafkaAdmin(configs);
    }

    /**
     * 创建 Topic
     */
    @Bean
    public NewTopic topicinfo() {
        // 创建topic,需要指定创建的topic的"名称"、"分区数"、"副本数量(副本数数目设置要小于Broker数量)"
        return new NewTopic(topic, 3, (short) 1);
    }

}

4.生产者配置

package com.example.dume.config;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

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


/**
 * @author dume
 * @create 2021-09-15 17:45
 **/

/**
 * 设置@Configuration、@EnableKafka两个注解,声明Config并且打开KafkaTemplate能力。
 */
@Configuration
@EnableKafka
public class KafkaProducerConfig {

    @Value("${kafkaserver.server}")
    private String boardServer;



    /**
     * Producer 参数配置
     */
    @Bean
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        // 指定多个kafka集群多个地址
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, boardServer);

        // 重试次数,0为不启用重试机制
        props.put(ProducerConfig.RETRIES_CONFIG, 0);
        //同步到副本, 默认为1
        // acks=0 把消息发送到kafka就认为发送成功
        // acks=1 把消息发送到kafka leader分区,并且写入磁盘就认为发送成功
        // acks=all 把消息发送到kafka leader分区,并且leader分区的副本follower对消息进行了同步就任务发送成功
        props.put(ProducerConfig.ACKS_CONFIG, "1");

        // 生产者空间不足时,send()被阻塞的时间,默认60s
        props.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, 6000);
        // 控制批处理大小,单位为字节
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, 4096);
        // 批量发送,延迟为1毫秒,启用该功能能有效减少生产者发送消息次数,从而提高并发量
        props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        // 生产者可以使用的总内存字节来缓冲等待发送到服务器的记录
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 40960);
        // 消息的最大大小限制,也就是说send的消息大小不能超过这个限制, 默认1048576(1MB)
        props.put(ProducerConfig.MAX_REQUEST_SIZE_CONFIG,1048576);
        // 键的序列化方式
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        // 值的序列化方式
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        // 压缩消息,支持四种类型,分别为:none、lz4、gzip、snappy,默认为none。
        // 消费者默认支持解压,所以压缩设置在生产者,消费者无需设置。
        props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"none");
        return props;
    }



    /**
     * Producer 工厂配置
     */
    @Bean
    public ProducerFactory<String, String> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    /**
     * Producer Template 配置
     */
    @Bean(name="kafkaTemplate")
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }



}

5.消费者配置

package com.example.dume.config;


import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;

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

/**
 * @author dume
 * @create 2021-09-15 17:45
 **/
@Configuration
@EnableKafka
public class KafkaConsumerConfig {

    @Value("${kafkaserver.server}")
    private String Server;

    @Value("${kafkaserver.group-id}")
    private String GroupId;



    @Bean
    KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory( ) {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        // 设置消费者工厂
        factory.setConsumerFactory(consumerFactory());
        // 消费者组中线程数量
        factory.setConcurrency(3);
        // 拉取超时时间
        factory.getContainerProperties().setPollTimeout(3000);
        //不自动启动
        factory.setAutoStartup(true);
        // 当使用批量监听器时需要设置为true
        factory.setBatchListener(true);
        return factory;
    }

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfigs());
    }

    @Bean
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> propsMap = new HashMap<>();
        // Kafka地址
        propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, Server);
        //配置默认分组,这里没有配置+在监听的地方没有设置groupId,多个服务会出现收到相同消息情况
        propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, GroupId);
        // 是否自动提交offset偏移量(默认true)
        propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
        //设置每次拉取最大数量
        propsMap.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG,1000);
        // 自动提交的频率(ms)
        propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100");
        // Session超时设置
        propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000");
        // 键的反序列化方式
        propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        // 值的反序列化方式
        propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        // offset偏移量规则设置:
        // (1)、earliest:当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,从头开始消费
        // (2)、latest:当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,消费新产生的该分区下的数据
        // (3)、none:topic各分区都存在已提交的offset时,从offset后开始消费;只要有一个分区不存在已提交的offset,则抛出异常
        propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
        return propsMap;
    }

}

6.生产者manager代码实现

package com.example.dume.manager;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author dume
 * @create 2021-09-24 9:43
 **/
@Service
public class KafkaProducerManager {
    private static Logger logger = LoggerFactory.getLogger("adminLogger");

    @Autowired
    @Qualifier("kafkaTemplate")
    private KafkaTemplate kafkaTemplate;
    /**
     * producer 同步方式发送数据
     *
     * @param topic   topic名称
     * @param message producer发送的数据
     */
    public void sendMessageSync(String topic, String message) throws InterruptedException, ExecutionException, TimeoutException {
        kafkaTemplate.send(topic, message).get(10, TimeUnit.SECONDS);
    }

    /**
     * producer 异步方式发送数据
     *
     * @param topic   topic名称
     * @param message producer发送的数据
     */
    public void sendMessageAsync(String topic, String message) {
        kafkaTemplate.send(topic, message).addCallback(new ListenableFutureCallback() {
            @Override
            public void onFailure(Throwable throwable) {
                logger.error("kafka send failure !");
            }

            @Override
            public void onSuccess(Object o) {
//                logger.info("kafka send  success !");

            }
        });
    }
}

7.消费者manager代码实现

package com.example.dume.manager;

import com.alibaba.fastjson.JSONObject;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.annotation.TopicPartition;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Optional;

/**
 * @author dume
 * @create 2021-09-16 9:06
 **/
@Component
public class KafkaComsumerManager {
    private static Logger logger = LoggerFactory.getLogger("adminLogger");


    private static  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * 指定topic
     * 指定消费分区parttition
     * @param records
     */
    @KafkaListener(topicPartitions = {
            @TopicPartition(topic = "${kafkaserver.topic}",  partitions = "${kafkaserver.parttition}" )},
            containerFactory = "kafkaListenerContainerFactory" )
    public void onMessage(List<ConsumerRecord> records) {
        logger.info("**********************************接收数量{}**************************************",records.size());
        for(ConsumerRecord record :records ){
            Optional<Object> kafkaMassage = Optional.ofNullable(record.value());
            if(kafkaMassage.isPresent()){
                try {
                    Long current = System.currentTimeMillis();
                    logger.info("**********************************kafka接收信息打印开始**************************************");
                    logger.info("kafka接收信息:"+'\t'+record.toString());
                    logger.info("kafka数据:"+'\t'+record.value());
                    logger.info("分区:"+ record.partition());
                    logger.info("偏移量:" + record.offset());
                    logger.info("报文时间:" + formatter.format(record.timestamp()));
                    logger.info("系统时间:" + formatter.format(current));
                    logger.info("**********************************kafka信息打印结束**************************************");
                    JSONObject value = JSONObject.parseObject(record.value().toString());

                } catch (Exception e) {
                    // TODO: handle exception
                    logger.error("********kafka接收数据出错:{}********",e.getMessage());
                }
            }


        }

    }

}

测试

编写测试接口

package com.example.dume.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.dume.manager.KafkaProducerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author dume
 * @create 2022-01-04 16:50
 **/
@RestController
@RequestMapping("/kafka")
public class KafkaController {
    private static Logger logger = LoggerFactory.getLogger("adminLogger");
    private static final String  producersuccess =" 生产数据到kafka成功!";

    @Value("${kafkaserver.topic}")
    private String topic;

    @Autowired
    private KafkaProducerManager kafkaProducerManager;

    @PostMapping(value = "/producerData")
    public JSONObject producerData(@RequestBody JSONObject object) {
        kafkaProducerManager.sendMessageAsync(topic,object.toJSONString());
        JSONObject o = new JSONObject();
        o.put("message",producersuccess);
        logger.info(producersuccess);
        return o;
    }
}

postman 接口测试向kafka插入数据:
在这里插入图片描述
使用kafkaTool查看插入数据:
在这里插入图片描述
消费者指定消费分区0内数据,消费者只接收到了 parttition=0的数据

2022-01-04 17:29:07.911  INFO 11104 --- [nio-8186-exec-2] adminLogger                              :  生产数据到kafka成功!
2022-01-04 17:30:34.465  INFO 11104 --- [nio-8186-exec-5] adminLogger                              :  生产数据到kafka成功!
2022-01-04 17:31:45.094  INFO 11104 --- [nio-8186-exec-8] adminLogger                              :  生产数据到kafka成功!
2022-01-04 17:31:45.104  INFO 11104 --- [ntainer#0-0-C-1] adminLogger                              : **********************************接收数量1**************************************
2022-01-04 17:31:45.104  INFO 11104 --- [ntainer#0-0-C-1] adminLogger                              : **********************************kafka接收信息打印开始**************************************
2022-01-04 17:31:45.104  INFO 11104 --- [ntainer#0-0-C-1] adminLogger                              : kafka接收信息:	ConsumerRecord(topic = dume-topic, partition = 0, leaderEpoch = 0, offset = 0, CreateTime = 1641288705094, serialized key size = -1, serialized value size = 36, headers = RecordHeaders(headers = [], isReadOnly = false), key = null, value = {"name":"老夫子","id":3,"age":70})
2022-01-04 17:31:45.104  INFO 11104 --- [ntainer#0-0-C-1] adminLogger                              : kafka数据:	{"name":"老夫子","id":3,"age":70}
2022-01-04 17:31:45.104  INFO 11104 --- [ntainer#0-0-C-1] adminLogger                              : 分区:0
2022-01-04 17:31:45.104  INFO 11104 --- [ntainer#0-0-C-1] adminLogger                              : 偏移量:0
2022-01-04 17:31:45.105  INFO 11104 --- [ntainer#0-0-C-1] adminLogger                              : 报文时间:2022-01-04 17:31:45
2022-01-04 17:31:45.106  INFO 11104 --- [ntainer#0-0-C-1] adminLogger                              : 系统时间:2022-01-04 17:31:45
2022-01-04 17:31:45.106  INFO 11104 --- [ntainer#0-0-C-1] adminLogger                              : **********************************kafka信息打印结束**************************************

代码地址

https://download.csdn.net/download/qq_38105536/73835664

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

springboot集成kafka实战项目,kafka生产者、消费者、创建topic,指定消费分区 的相关文章

  • 在不支持 CAS 操作的处理器上进行 CompareAndSet

    今天 我在一次采访中被问到下一个问题 如果您在具有不支持 CAS 操作的处理器的机器上调用 AtomicLong 的compareAndSet 方法 会发生什么情况 您能否帮我解决这个问题 并在可能的情况下提供一些全面描述的链接 From
  • Kafka - 如何同时使用过滤器和过滤器?

    我有一个 Kafka 流 它从一个主题获取数据 并且需要将该信息过滤到两个不同的主题 KStream
  • Java 中的 <-- 是什么? [复制]

    这个问题在这里已经有答案了 我遇到了下面的片段 它输出到4 3 2 1 我从来没有遇到过 lt 在爪哇 Is lt 使 var1 的值变为 var2 的运算符 public class Test public static void mai
  • 查看Java Agent修改的Java类的源代码

    我需要了解 Java 代理如何修改我的初始类 以便我能够理解代码的作用 build gradle configurations jar archiveName agent2 jar jar manifest attributes Prema
  • 无法使用 datastax java 驱动程序通过 UDT 密钥从 cassandra 检索

    我正在尝试使用用户定义的类型作为分区键将对象存储在 cassandra 中 我正在使用 datastax java 驱动程序进行对象映射 虽然我能够插入到数据库中 但无法检索该对象 如果我更改分区键以使用非 udt 例如文本 我就能够保存和
  • java中如何知道一条sql语句是否执行了?

    我想知道这个删除语句是否真的删除了一些东西 下面的代码总是执行 else 是否删除了某些内容 执行此操作的正确方法是什么 public Deleter String pname String pword try PreparedStatem
  • Spring boot 2.3 中找不到 javax.validation [重复]

    这个问题在这里已经有答案了 升级到 Spring Boot 2 3 1 后javax validation找不到包
  • 如何使用 Java 引用释放 Java Unsafe 内存?

    Java Unsafe 类允许您按如下方式为对象分配内存 但是使用此方法在完成后如何释放分配的内存 因为它不提供内存地址 Field f Unsafe class getDeclaredField theUnsafe Internal re
  • getCurrentSession 在网络中休眠

    我正在使用 hibernate 和 jsp servlet 编写一个基于 Web 的应用程序 我读过有关sessionFactory getCurrentSession and sessionFactory openSession方法 我知
  • Java AES 256 加密

    我有下面的 java 代码来加密使用 64 个字符密钥的字符串 我的问题是这会是 AES 256 加密吗 String keyString C0BAE23DF8B51807B3E17D21925FADF273A70181E1D81B8EDE
  • 无需递归即可对可观察结果进行分页 - RxJava

    我有一个非常标准的 API 分页问题 您可以通过一些简单的递归来处理 这是一个捏造的例子 public Observable
  • 数据库中的持久日期不等于检索日期

    我有一个具有 Date 属性的简单实体类 此属性对应于 MySQL 日期时间列 Entity public class Entity Column name start date Temporal TemporalType TIMESTAM
  • Java 8 Stream,获取头部和尾部

    Java 8 引入了Stream http download java net jdk8 docs api java util stream Stream html类似于 Scala 的类Stream http www scala lang
  • Android计算两个日期之间的天数

    我编写了以下代码来查找两个日期之间的天数 startDateValue new Date startDate endDateValue new Date endDate long diff endDateValue getTime star
  • 我所有的 java 应用程序现在都会抛出 java.awt.headlessException

    所以几天前我有几个工作Java应用程序使用Swing图书馆 JFrame尤其 他们都工作得很好 现在他们都抛出了这个异常 java awt headlessexception 我不知道是什么改变了也许我的Java版本不小心更新了 谢谢你尽你
  • 使用 Apache 允许 Glassfish 和 PHP 在同一服务器中协同工作

    是否可以建立从 Java 到 php 文件的桥梁 我有一个用 Java 编写的应用程序 我需要执行http piwik org http piwik org 这是用 PHP 编写的 在服务器中 我正在运行 PHP 但无法从浏览器访问 php
  • 如何让 Firebase 与 Java 后端配合使用

    首先 如果这个问题过于抽象或不适合本网站 我想表示歉意 我真的不知道还能去哪里问 目前我已经在 iOS 和 Android 上开发了应用程序 他们将所有状态保存在 Firebase 中 因此所有内容都会立即保存到 Firebase 实时数据
  • 使用 DBCP 配置 Tomcat

    在闲置一段时间 几个小时 后 我们收到了 CommunicationsException 来自 DBCP 错误消息 在异常中 位于这个问题的末尾 但我没有看到任何配置文件中定义的 wait timeout 我们应该看哪里 在 tomcat
  • Spring 作为 JNDI 提供者?

    我想使用 Spring 作为 JNDI 提供程序 这意味着我想在 Spring 上下文中配置一个 bean 可以通过 JNDI 访问该 bean 这看起来像这样
  • 设置 TreeSet 的大小

    有没有办法像数组一样对 Java 集合中的 TreeSet 进行大小限制 例如我们在数组中 anArray new int 10 数组具有固定长度 在创建数组时必须指定该长度 A TreeSet当您向其中添加元素时会自动增长 您无法设置其大

随机推荐

  • 九龙战登录只显示一个服务器,九龙战登录失败进不去解决办法

    九龙战是腾讯推出的一款三国题材的动作竞技手游 目前已经开启了不删档测试 但是玩家们在游戏中遇到了登录失败进不去的情况 下面小编就为大家介绍一下九龙战登录失败进不去解决办法 首先玩家们要知道九龙战是一款不删档测试不久的游戏 所以在这期间出现什
  • Android基于BroadcastReceiver和Service、SoundPool开发的防过充助手app

    前段时间换了一个小米4C手机 可是发现它的充电充满没有提醒 上一个手机换了就是因为不爱惜电池 让它过充的次数多了 虽然听别人说小米4c手机充电器是智能充电器 有保护作用 但我自己还是不放心 于是就亲手写了一个防过充小应用 已经在使用 可以达
  • 如何使用LaTeX制作PPT?

    作为LaTeX排版软件 LaTeX主要被用来制作书籍和文章 但由于现代LaTeX系统主要以PDF文件为输出方式 授课 演讲用的计算机幻灯片也日益成为LaTeX的一个重要应用 LaTeX中专门用来制作幻灯片的工具有powerdot文档类 pr
  • 探索.NET:​构建现代软件开发的核心框架

    摘要 在现代软件开发领域 选择一个合适的开发框架对于成功构建可靠 高效的应用程序至关重要 NET 读作 dot net 是一个强大而广泛使用的框架 为开发人员提供了丰富的工具和功能 以简化开发过程并加快交付时间 本文将介绍 NET的基本概念
  • 【手撕RPC服务分几步】

    手撕RPC服务分几步 前言 什么是RPC 从被调用方 provider 来说 从调用方 consumer 来说 扩展思考 dubbo架构图 前言 本文试图通过手撕RPC的理论步骤来帮助我们更好的理解其特性 也更好的理解像Dubbo sofa
  • flutter 填坑之旅(dart学习笔记篇)

    俗话说 工欲善其事必先利其器 想要撸flutter app 而不懂 dart 那就像一个不会英语的人在和英国人交流 懵 安装 dart 就不用说了 比较简单dart 官网 https dart dev 安装完成后就开启学习dart 旅程吧
  • MyEclipse配置Tomcat7

    首先我们打开Myeclipse 进入偏好设置window gt perferences 进入偏好设置 perferences 在偏好设置的搜索栏那里输入tomcat查找tomcat 如下图所示 3 我们可以看到搜索到的有四个tomcat项
  • (笔试前准备)字符串匹配算法总结

    我想说一句 我日 我讨厌KMP KMP虽然经典 但是理解起来极其复杂 好不容易理解好了 便起码来巨麻烦 老子就是今天图书馆在写了几个小时才勉强写了一个有bug的 效率不高的KMP 特别是计算next数组的部分 其实 比KMP算法速度快的算法
  • STM32 HAL库更改中断向量表的偏移地址

    以STM32F767为例 打开system stm32f7xx c文件 定位VECT TAB OFFSET 更改此宏定义的值 即可更改偏移量
  • 富维火焰识别算法

    火灾是威胁公共安全 危害人民生命财产的灾害之一 加强消防安全管理是头等大事 对火灾做到早预防 早发现 尽量避免火灾的发生尤为重要 近年来随着网络摄像机的广泛使用以及图像处理技术的不断发展 基于视频的北京富维图像火焰识别算法得到了越来越多的关
  • Android Rom修改制作工具软件集合

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 1 SIN2IMG 用于固件ftf中system sin的解包 下载地址 SIN2IMG rar 使用方法 将固件ftf文件用rar打开 解压出system sin文件 将
  • Idea 修改默认的Maven配置及修改为阿里源

    每次使用Idea创建或者导入Maven项目的时候 Idea都会使用系统默认的Maven 此时 如果我们想使用自定义安装的Maven 需要在File gt other settings gt Settings for New Projects
  • STM32-custom usb

    如何建立一个自定义的HID工程呢 下面就来讲讲 首先先介绍下工程的架构 工程的总体架构下图所示 按照下图架构建工程 分析下工程布局 首先是APP 这个组里存放着主文件mian c 管理所有中断服务程序stm3210x it c 及其管理外设
  • PageObjects支持库-Poium使用方法

    PO模式 学过自动化的都知道PageObjects模式 将页面对象封装为类 页面元素和操作封装为类的属性和方法 在测试方法中调用页面对象进行测试 关于PO模式可见 http t csdn cn 0DBlP 在PO模式下 我们一般定义个一个基
  • 想写一本书,而这是序言

    口袋书 序言 现在的风口是什么 很多人会答人工智能 Artificial Intelligence AI 人工智能是一项伟大的发明 我们不得不承认 它已经为社会带来了翻天覆地的变化 并 将在未来卷起更大的风暴 不了解人工智能 就难以在这个
  • 前端js将扁平化数据转化为=菜单树

    let menuList id 1 pid 1 name 江西 id 2 pid 1 name 南昌 id 3 pid 1 name 九江 id 4 pid 1 name 广东 id 5 pid 4 n
  • 【考研】数据结构——线索二叉树

    CSDN话题挑战赛第2期 参赛话题 学习笔记 前言 本文内容源于对 数据结构 C语言版 第2版 王道讲解学习所得心得 笔记整理和总结 本文针对线索二叉树 在最后的练习中 以举例子说明该排序方法 配以图文 讲解详细 含408真题 可搭配以下链
  • 学校与工作(献于在校大学生及入职不久的工作者)

    学校与工作 每个人都把自己眼界的局限当成世界的局限 学校是非常不同于职业工作的 有些人在其早期职业生涯中栽跟头 就是因为未能从已经生活了近20年的学校环境过渡到软件行业的美丽新世界 学生的活动具有高度约束性 工作量都是规定好了的 虽然当你是
  • IEEE-754标准浮点数,十六进制与十进制转换方法(附C代码)

    十进制数与IEEE 754 32 位转换实例讲解 https blog csdn net qq 41629142 article details 83692106 https blog csdn net a627088424 article
  • springboot集成kafka实战项目,kafka生产者、消费者、创建topic,指定消费分区

    springboot集成kafka实战项目 kafka生产者 消费者 创建topic 指定消费分区 前言 本项目代码可直接集成到你现有的springboot项目中 功能包括 1 kafka生产者配置 2 kafka消费者配置 指定分区消费