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发送消息的完整例子。你可以根据自己的需求进行修改和扩展。

相关推荐
像颗糖4 分钟前
Docker 与 Docker Compose 通用实战指南(从安装到区别)
后端
Memory_荒年8 分钟前
Spring Security + OAuth2 + JWT:三剑客合璧,打造“无懈可击”的微服务安全防线
java·后端·spring
Loadings1 小时前
聊聊 AI Coding 的最新范式:Harness Engineering:我们这群程序员,又要继续学了?
前端·后端
ssshooter1 小时前
哈希是怎么被破解的?
前端·后端
荒古前1 小时前
Spring Boot + MyBatis 启动报错:不允许有匹配 “[xX][mM][lL]“ 的处理指令目标
spring boot·后端·mybatis
mldlds1 小时前
Spring Boot 实战:轻松实现文件上传与下载功能
java·数据库·spring boot
xxjj998a1 小时前
Spring Boot 整合 Apollo 配置中心实战
java·spring boot·后端
苏三说技术1 小时前
千万数量级excel,如何快速导入?
后端
徐小夕2 小时前
一个普通Word文档,为什么99%的开源编辑器都"认怂"了?我们选择正面硬刚
vue.js·后端·github
splage2 小时前
SpringBoot 与 SpringCloud的版本对应详细版
spring boot·后端·spring cloud