springboot 2.6.x 整合 2.8.0kafka

springboot 2.6.x 整合 2.8.0kafka

  • 前言
  • 一、kafka是什么?
  • 二、kafka安装(踩坑)
    • 1.kafka下载地址
    • 2.修改kafka内置的zk配置文件(默认无需修改)
    • 3.启动zk
    • 4.修改kafka server.properties配置文件(很重要,会有很多问题)
    • 5.启动kafka,在Kafka目录下执行即可
  • 三、使用步骤
    • 1.引入库
    • 2.yml添加配置
    • 3.kafka配置类,推荐kafka的topic在配置类中创建,后面易于维护和管理
    • 4.开始使用生产者
    • 5.开始使用消费者
  • 四、在服务器上通过指令执行命令
    • 1.查看zk已经创建了多少个topic
    • 2.创建/删除Topic
    • 3.创建生产者,给topic推送消息(避坑:推送消息的时候需要加上'content',否则报错。切记)
    • 4.创建消费者,监听即可
  • 总结


前言


一、kafka是什么?

Kafka 本质上是⼀个消息队列。与zeromq不同的是,Kafka是一个独立的框架而不是一个库。这里主要介绍其原理,至于具体的安装等操作不做介绍,只是提示一下,第一次运行时,先设置前台运行,看会不会报错。

二、kafka安装(踩坑)

1.kafka下载地址

https://kafka.apache.org/downloads

2.修改kafka内置的zk配置文件(默认无需修改)

# 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=/kingpi/kafka/data
# 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

3.启动zk

./bin/zookeeper-server-start.sh -daemon /kingpi/kafka/kafka_2.12-2.8.2/config/zookeeper.properties

4.修改kafka server.properties配置文件(很重要,会有很多问题)

#默认0,有集群的话会有1,2等。每个broker都要唯一哈,否则起不来的。
broker.id=0
#需要这样配置到当前服务器上,切记//后面无需加参数即可
listeners=PLAINTEXT://:9092
#需要配置当前的服务器IP用于外部客户端使用,否则会提示无法连接,启动spring boot的时候会连接本地的kafka导致无法连接的错误:[Producer clientId=producer-1] Error while fetching metadata with correlation id 95 : {topic=INVALID_REPLICATION_FACTOR}
advertised.listeners=PLAINTEXT://CURRENT_IP:9092
#连接指定的zk即可
zookeeper.connect=localhost:2181

5.启动kafka,在Kafka目录下执行即可

./bin/kafka-server-start.sh -daemon  /kingpi/kafka/kafka_2.12-2.8.2/config/server.properties

三、使用步骤

1.引入库

代码如下(示例):

<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>
  <version>2.8.0</version>
</dependency>

2.yml添加配置

代码如下(示例):

server:
  port: 8989
  servlet:
    context-path: /

spring:
  application:
    name: kafka-service
  kafka:
    bootstrap-servers: IP:9092
    producer: # producer 生产者
      retries: 0 # 重试次数
      acks: 1 # 应答级别:多少个分区副本备份完成时向生产者发送ack确认(可选01、all/-1)
      batch-size: 16384 # 批量大小
      buffer-memory: 33554432 # 生产端缓冲区大小
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.apache.kafka.common.serialization.StringSerializer
    consumer: # consumer消费者
      group-id: javagroup # 默认的消费组ID
      enable-auto-commit: true # 是否自动提交offset
      auto-commit-interval: 100  # 提交offset延时(接收到消息后多久提交offset)
      # earliest:当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,从头开始消费
      # latest:当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,消费新产生的该分区下的数据
      # none:topic各分区都存在已提交的offset时,从offset后开始消费;只要有一个分区不存在已提交的offset,则抛出异常
      auto-offset-reset: latest
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer

3.kafka配置类,推荐kafka的topic在配置类中创建,后面易于维护和管理

package com.hh.kafka.config;

import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.TopicBuilder;


/**
 * @Description: kafka配置类
 * @Author: raoqinhao
 * @Date: 2022-12-30 15:52
 */
@Configuration
public class KafkaConfig {

    @Bean
    public NewTopic topic() {
        return TopicBuilder.name("topic").build();
    }

}

4.开始使用生产者

package com.hh.kafka.controller;

import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Description: TODO
 * @Author: raoqinhao
 * @Date: 2022-12-30 15:50
 */
@RestController
@RequestMapping("/kafka")
public class KafkaController {

    @Resource
    public KafkaTemplate<String, String> kafkaTemplate;

    @PostMapping("/sendMessage")
    public Boolean productMessage() {
        String data = "{\"name\":\"zhangsan\"}";
        kafkaTemplate.send("topic", data); // 注意这里发送这个topic如果不存在会自动创建的,存在就不会。
        return Boolean.TRUE;
    }

}

5.开始使用消费者

package com.hh.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @Description: TODO
 * @Author: raoqinhao
 * @Date: 2022-12-30 15:55
 */
@Component
public class KafkaConsumer {

    @KafkaListener(topics = {"topic"}, groupId = "javagroup")
    public void onMessage1(ConsumerRecord<?, ?> record){
        // 消费的哪个topic、partition的消息,打印出消息内容
        System.out.println("简单消费:"+record.topic()+"-"+record.partition()+"-"+record.value());
    }

}

四、在服务器上通过指令执行命令

1.查看zk已经创建了多少个topic

[root@localhost kafka_2.12-2.8.2]# ./bin/kafka-topics.sh --zookeeper 127.0.0.1:2181 --list

2.创建/删除Topic

[root@localhost kafka_2.12-2.8.2]# ./bin/kafka-topics.sh --create --topic topic --partitions 1 --replication-factor 1 --zookeeper localhost:2181
[root@localhost kafka_2.12-2.8.2]# ./bin/kafka-topics.sh --delete --topic topic --zookeeper localhost:2181

3.创建生产者,给topic推送消息(避坑:推送消息的时候需要加上’content’,否则报错。切记)

[root@localhost kafka_2.12-2.8.2]# ./bin/kafka-console-producer.sh --broker-list localhost:9092 --topic topic

4.创建消费者,监听即可

[root@localhost kafka_2.12-2.8.2]# ./bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic topic --from-beginning

总结

人生路上遇风雨,才发现,路必须自己走,苦必须自己受;生活路上有苦甜,才发现,伤必须自己舔,槛必须自己过。人生是一种平衡,你拥有了这样,必然会错过那样;你什么都想得到,结果通常会失去更多。不必奢求人生中有绝对的公平,公平就如天平的两端,一端的付出越多,别一端才可以承载更多的希冀。

你可能感兴趣的:(spring,boot,kafka,java)