spring boot kafka 代码样例
时间: 2023-08-01 13:06:26 浏览: 107
以下是一个简单的 Spring Boot 和 Kafka 整合的代码样例:
首先,确保在项目的 pom.xml 文件中添加了 Kafka 的依赖项:
```xml
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
```
然后,创建一个 KafkaProducerConfig 类来配置 Kafka 生产者:
```java
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class KafkaProducerConfig {
@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);
}
@Bean
public KafkaTemplate<String, String> kafkaTemplate() {
return new KafkaTemplate<>(producerFactory());
}
}
```
接下来,创建一个 KafkaProducerController 类来定义一个简单的 REST 接口用于发送消息:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class KafkaProducerController {
private final KafkaTemplate<String, String> kafkaTemplate;
@Autowired
public KafkaProducerController(KafkaTemplate<String, String> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
@PostMapping("/sendMessage")
public String sendMessage(@RequestBody String message) {
kafkaTemplate.send("my_topic", message);
return "Message sent successfully!";
}
}
```
最后,在启动类中添加 `@EnableKafka` 注解来启用 Kafka 的功能:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.EnableKafka;
@SpringBootApplication
@EnableKafka
public class KafkaDemoApplication {
public static void main(String[] args) {
SpringApplication.run(KafkaDemoApplication.class, args);
}
}
```
这样,您就可以通过发送 POST 请求到 `/sendMessage` 接口来向 Kafka 的 `my_topic` 主题发送消息了。
请注意,以上代码仅为示例,实际使用中可能需要根据您的具体需求进行适当的修改和扩展。
阅读全文