当前位置: 首页> 汽车> 维修 > linux 部署mosquitto外部连接到MySQL数据库记录mqtt消息

linux 部署mosquitto外部连接到MySQL数据库记录mqtt消息

时间:2025/7/10 2:29:22来源:https://blog.csdn.net/qq_40987844/article/details/140849047 浏览次数: 0次

1.安装python3.7.x

2.pip3 install mysql-server python3-mysqldb

pip3 install 包名 -i https://mirrors.aliyun.com/pypi/simple/
用阿里镜像

3.pip3 install paho-mqtt -i https://mirrors.aliyun.com/pypi/simple/

4.修改配置文件

vim mosquitto.conf

#配置信息
persistence true
persistence_location /var/lib/mosquitto/
log_type all
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d

没有的文件夹创建一下。没有的文件创建一下

5.编写python脚本

vim mosquitto_mysql.py

import paho.mqtt.client as mqtt
import mysql.connector
from mysql.connector import Error

# MySQL数据库连接信息
db_config = {
    "host": "ip",
    "user": "root",
    "password": "密码",
    "database": "数据库"
}

# Mosquitto回调函数
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("#")  # 订阅所有主题

def on_message(client, userdata, msg):
    try:
        # 连接到MySQL数据库
        connection = mysql.connector.connect(**db_config)
        if connection.is_connected():
            cursor = connection.cursor()
            # 插入消息到数据库
            query = "INSERT INTO mqtt_messages (topic, payload) VALUES (%s, %s)"
            values = (msg.topic, msg.payload.decode("utf-8"))
            cursor.execute(query, values)
            connection.commit()
            print("Message saved to database: ", msg.topic, msg.payload)
    except Error as e:
        print("Error while connecting to MySQL", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

# 创建Mosquitto客户端实例
client = mqtt.Client(client_id="主机id")
client.on_connect = on_connect
client.on_message = on_message

# 连接到Mosquitto代理(请替换为您的代理地址和端口)
client.username_pw_set("用户名", "密码")
client.connect("ip", 1883, 60)

# 开始监听消息
client.loop_forever()

6.python3 mosquitto_mysql.py
运行报错,缺少的依赖自己装一下

关键字:linux 部署mosquitto外部连接到MySQL数据库记录mqtt消息

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: