SpringBoot整合KafKa

一、前言

Kafka是由Apache软件基金会开发的一个开源流处理平台,由Scala和Java编写。Kafka是一种高吞吐量的分布式发布订阅消息系统,它可以处理消费者在网站中的所有动作流数据。 这种动作(网页浏览,搜索和其他用户的行动)是在现代网络上的许多社会功能的一个关键因素。 这些数据通常是由于吞吐量的要求而通过处理日志和日志聚合来解决。 对于像Hadoop一样的日志数据和离线分析系统,但又要求实时处理的限制,这是一个可行的解决方案。Kafka的目的是通过Hadoop的并行加载机制来统一线上和离线的消息处理,也是为了通过集群来提供实时的消息。

二、搭建KafKa开发环境

•JDK环境

•Zookeeper环境(至少单节点)

•KafKa环境

三、入门案例

3.1、改pom


        <!--GSON-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <!--转json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.59</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>


3.2、新建application.yml

server:
  port: 8090
#  servlet:
#    context-path: /es

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource    # 配置当前要使用的数据源的操作类型
    driver-class-name: com.mysql.jdbc.Driver      # 配置MySQL的驱动程序类
    url: jdbc:mysql://127.0.0.1:3306/aaa?useUnicode=true&characterEncoding=utf8
    username: root                                  # 数据库用户名
    password: 159728                     # 数据库连接密码
    dbcp2:                                          # 进行数据库连接池的配置
      min-idle: 5                                   # 数据库连接池的最小维持连接数
      initial-size: 5                               # 初始化提供的连接数
      max-total: 5                                  # 最大的连接数
      max-wait-millis: 200                          # 等待连接获取的最大超时时间
  thymeleaf:
    #模板的模式,支持 HTML, XML TEXT JAVASCRIPT
    mode: HTML5
    #编码 可不用配置
    encoding: UTF-8
    #开发配置为false,避免修改模板还要重启服务器
    cache: false
    #配置模板路径,默认是templates,可以不用配置
    prefix: classpath:/templates/
    suffix: .html
  mvc:
    date-format: yyyy-MM-dd
  kafka:
    bootstrap-servers: 127.0.0.1:9092  #指定kafka server的地址,集群配多个,中间,逗号隔开
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.apache.kafka.common.serialization.StringSerializer
    consumer:
      group-id: test-consumer
      auto-offset-reset: latest
      enable-auto-commit: true
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer

#elasticsearch:
#  host: 111.229.170.222
#  port: 9200
#  schema: http
#  username: elastic
#  password: admin123

mybatis:
  config-location: classpath:mybatis.cfg.xml    # mybatis配置文件所在路径
  type-aliases-package: com.example.esdemo.*.pojo            # 定义所有操作类的别名所在包
  mapper-locations: mapper/*/*.xml
logging:
  level:
    com.example.demo: debug
  config: classpath:logback.xml

#fastdfs 配置
fdfs:
  # 读取时间
  so-timeout: 3000
  # 连接超时时间
  connect-timeout: 3000
  # 缩略图
  thumb-image:
    width: 150
    height: 150
  # Tracker服务
  tracker-list:
    - 127.0.0.1:22122

3.3、建主启动类

package com.example.esdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class EsDemoApplication {

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

}

3.4、建KafKa生产者

package com.example.esdemo.kafka;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author wzh
 * @create 2022-09-12 0:23
 * 消息发送
 */
@RestController
@Slf4j
public class KafKaProductController {

    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    @GetMapping("send/{message}")
    public void send(@PathVariable String message) {
        ListenableFuture<SendResult<String, String>> future = this.kafkaTemplate.send("topic01", message);
        future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
            @Override
            public void onSuccess(SendResult<String, String> result) {
                log.info("成功发送消息:{},offset=[{}]", message, result.getRecordMetadata().offset());
            }

            @Override
            public void onFailure(Throwable ex) {
                log.error("消息:{} 发送失败,原因:{}", message, ex.getMessage());
            }
        });
    }
}

3.5、建KafKa消费者

package com.example.esdemo.kafka;

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

/**
 * @author wzh
 * @create 2022-09-12 0:25
 * 消费者
 */
@Component
@Slf4j
public class KafKaConsumerListener {
    @KafkaListener(topics = "topic01", groupId = "test-consumer")
    public void listen(ConsumerRecord<?, ?> record) {
        log.info("接收消息: topic is {}, offset is {}, partition is {}, value is {} ", record.topic(), record.offset(), record.partition(), record.value());
    }
}

3.6、测试KafKa生产者、消费者能力

test.png

posted on 2026-08-10 15:36  爱河  阅读(2)  评论(0)    收藏  举报

导航