Kafka和MySQL的组合使用代码示例
时间: 2023-06-24 11:05:48 浏览: 343
以下使用Kafka和MySQL的组合使用代码示例。该示例使用Python编写。
```
from kafka import KafkaConsumer
import mysql.connector
# 创建Kafka消费者
consumer = KafkaConsumer('my_topic', bootstrap_servers=['localhost:9092'])
# 连接MySQL数据库
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# 获取数据库游标
cursor = db.cursor()
# 处理Kafka消息
for message in consumer:
# 将消息插入MySQL数据库
sql = "INSERT INTO my_table (message) VALUES (%s)"
val = (message.value,)
cursor.execute(sql, val)
db.commit()
```
该示例首先创建了一个Kafka消费者,然后连接到MySQL数据库。在处理Kafka消息时,它将每个消息插入到MySQL数据库中。请注意,这只是一个简单的示例,您需要根据您的实际需求进行修改。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)