springboot kafka 发送消息
时间: 2023-08-31 13:09:28 浏览: 87
在Spring Boot中使用Kafka发送消息,需要先在pom.xml中添加Kafka依赖:
```
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
```
然后,在application.properties或application.yml文件中配置Kafka的连接信息:
```
spring.kafka.bootstrap-servers=localhost:9092
```
接着,在Spring Boot应用程序中创建一个KafkaTemplate的Bean:
```
@Configuration
public class KafkaProducerConfig {
@Bean
public KafkaTemplate<String, String> kafkaTemplate() {
return new KafkaTemplate<>(producerFactory());
}
@Bean
public ProducerFactory<String, String> producerFactory() {
Map<String, Object> configProps = new HashMap<>();
configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
return new DefaultKafkaProducerFactory<>(configProps);
}
}
```
最后,在需要发送消息的地方注入KafkaTemplate并调用send方法:
```
@Service
public class KafkaProducer {
private static final String TOPIC = "test";
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String message) {
kafkaTemplate.send(TOPIC, message);
}
}
```
这样就可以使用KafkaTemplate发送消息到指定的topic了。
阅读全文
相关推荐


















