spring boot kafka 发送消息 完整的例子工程

以下是一个简单的Spring Boot Kafka发送消息的完整例子:

首先,添加Spring Boot Kafka的依赖到你的pom.xml文件:

复制代码
xml
<dependencies>  
    <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-kafka</artifactId>  
    </dependency>  
</dependencies>

在application.properties文件中配置Kafka的相关属性:

复制代码
properties
spring.kafka.bootstrap-servers=localhost:9092  
spring.kafka.consumer.group-id=test-group  
spring.kafka.template.default-topic=test-topic

创建一个Kafka生产者类,并注入KafkaTemplate:

复制代码
java
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.kafka.core.KafkaTemplate;  
import org.springframework.stereotype.Service;  
  
@Service  
public class KafkaProducerService {  
    @Autowired  
    private KafkaTemplate<String, String> kafkaTemplate;  
  
    public void sendMessage(String message) {  
        kafkaTemplate.send("test-topic", message);  
    }  
}

在你的Spring Boot应用程序中,你可以调用sendMessage方法发送消息:

复制代码
java
@Autowired  
private KafkaProducerService kafkaProducerService;  
  
public static void main(String[] args) {  
    SpringApplication.run(MyApplication.class, args);  
    KafkaProducerService kafkaProducerService = SpringApplicationContext.getBean(KafkaProducerService.class);  
    kafkaProducerService.sendMessage("Hello, Kafka!");  
}

以上是一个简单的Spring Boot Kafka发送消息的完整例子。你可以根据自己的需求进行修改和扩展。

相关推荐
eqwaak013 小时前
4 月技术快讯|Rust 1.90 正式发布,系统级开发再进化
开发语言·后端·rust
大鸡腿同学13 小时前
人选天选
后端
Victor35614 小时前
MongoDB(107)如何使用MongoDB Compass?
后端
皮皮林5511 天前
SpringBoot + Disruptor 实现特快高并发处理,支撑每秒 600 万订单无压力!
spring boot
阿丰资源1 天前
基于SpringBoot的在线视频教育平台的设计与实现(附源码+数据库+文档,一键运行)
数据库·spring boot·后端
苍煜1 天前
ThreadPoolExecutor线程池终极全解:同步异步判定+SpringBoot生产实战
java·开发语言·spring boot
IT_陈寒1 天前
我竟然被JavaScript的隐式类型转换坑了三天!
前端·人工智能·后端
Reart1 天前
从0解构tinyWeb项目--(Day:9)
后端·架构·github
小码哥_常1 天前
Java后端定时任务“三剑客”大比拼,选对不选贵!
后端
oldking呐呐1 天前
MySQL从入门到入土 -- 2.数据库基础
后端·mysql