展示一下springboot整合kafka示例代码
时间: 2023-09-06 11:08:26 浏览: 102
以下是一个简单的Spring Boot应用程序,演示了如何使用Kafka生产者和消费者。
1. 添加Kafka依赖
```xml
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
```
2. 配置Kafka
```yaml
spring:
kafka:
bootstrap-servers: localhost:9092
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.apache.kafka.common.serialization.StringSerializer
consumer:
group-id: test-group
auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
```
3. 编写Kafka生产者
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class KafkaProducer {
private static final String TOPIC = "test-topic";
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String message) {
this.kafkaTemplate.send(TOPIC, message);
}
}
```
4. 编写Kafka消费者
```java
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
public class KafkaConsumer {
@KafkaListener(topics = "test-topic", groupId = "test-group")
public void consume(String message) {
System.out.println("Received message: " + message);
}
}
```
5. 测试
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class KafkaDemoApplication implements CommandLineRunner {
@Autowired
private KafkaProducer kafkaProducer;
public static void main(String[] args) {
SpringApplication.run(KafkaDemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
kafkaProducer.sendMessage("Hello, Kafka!");
}
}
```
在运行应用程序后,将打印出接收到的消息。
阅读全文