SpringBoot集成kafka接收对象消息

SpringBoot集成kafka接收对象消息

1、生产者

java 复制代码
package com.power.producer;

import com.power.model.User;
import com.power.util.JSONUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
public class EventProducer {

    @Resource
    private KafkaTemplate<String,Object> kafkaTemplate;

    public void sendEvent2(){
        User user = User.builder().id(10001).phone("15676767676").birthday(new Date()).build();
        String userJson = JSONUtils.toJSON(user);
        kafkaTemplate.send("helloTopic",userJson);
    }

}

2、消费者

java 复制代码
package com.power.consumer;

import com.power.model.User;
import com.power.util.JSONUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.function.Consumer;

@Component
public class EventConsumer {

    //采用监听的方式接收事件(消息,数据)
    @KafkaListener(topics = {"helloTopic"},groupId="helloGroup")
        public void onEvent(String userJson,
                        @Header(value=KafkaHeaders.RECEIVED_TOPIC) String topic,
                        @Header(value=KafkaHeaders.RECEIVED_PARTITION_ID) String partition,
                        ConsumerRecord<String,String> record){
        User user =JSONUtils.toBean(userJson,User.class);
        System.out.println("读取/消费到的事件,user:"+user+",topic:"+topic+",partition:"+partition);
        System.out.println("读取/消费到的事件:"+record.toString());

    }

}

3、工具类

java 复制代码
package com.power.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONUtils {

    private static final ObjectMapper OBJECTMAPPER = new ObjectMapper();

    public static String toJSON(Object object){
        try {
            return OBJECTMAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T toBean(String json,Class<T> clazz){
        try {
            return OBJECTMAPPER.readValue(json,clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}

4、消息实体对象

java 复制代码
package com.power.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {

    private Integer id;

    private String phone;

    private Date birthday;

}

5、配置文件

java 复制代码
spring:
  application:
    #应用名称
    name: spring-boot-02-kafka-base

  #kafka连接地址(ip+port)
  kafka:
    bootstrap-servers: <你的kafka服务器IP>:9092

6、启动类

java 复制代码
package com.power;

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

@SpringBootApplication
public class KafkaApplication {

	public static void main(String[] args) {
		SpringApplication.run(KafkaApplication.class, args);
		System.out.println("启动成功--------------------------");
	}
}

7、测试类

java 复制代码
package com.power;

import com.power.producer.EventProducer;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@SpringBootTest
public class SpringBoot02KafkaBaseApplication {

    @Resource
    private EventProducer eventProducer;

    @Test
    void sendEvent2(){
        eventProducer.sendEvent2();
    }

}

8、测试结果

先启动消费者

在启动生产者测试类

已接收到消息对象数据:

相关推荐
wudl55662 小时前
flink 1.20 物化表(Materialized Tables)
大数据·flink·linq
Q_Q5110082852 小时前
python+django/flask的眼科患者随访管理系统 AI智能模型
spring boot·python·django·flask·node.js·php
韩立学长4 小时前
基于Springboot的旧时月历史论坛4099k6s9(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
Q_Q5110082854 小时前
python+django/flask的在线学习系统的设计与实现 积分兑换礼物
spring boot·python·django·flask·node.js·php
Q_Q5110082855 小时前
python+django/flask的车辆尾气检测排放系统-可视化大屏展示
spring boot·python·django·flask·node.js·php
汤姆yu5 小时前
基于SpringBoot的动漫周边商场系统的设计与开发
java·spring boot·后端
摇滚侠7 小时前
Spring Boot3零基础教程,响应式编程的模型,笔记109
java·spring boot·笔记
Q_Q19632884758 小时前
python+django/flask基于Echarts+Python的图书零售监测系统设计与实现(带大屏)
spring boot·python·django·flask·node.js·php
拾荒的小海螺8 小时前
JAVA:Spring Boot3 新特性解析的技术指南
java·开发语言·spring boot
L.EscaRC9 小时前
Spring Boot 自定义组件深度解析
java·spring boot·后端