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

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
运行报错,缺少的依赖自己装一下

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值