mqtt意为消息队列遥测传输,是IBM开发的一个即时通信协议。因为其维护一个长链接以轻量级低消耗著称,因此经常使用于移动端消息推送服务开发。vim
mqtt协议控制报文的格式包含三部分:
以固定报头、可变报头和有效载荷,其中固定报文头是全部控制报文都有的,可变报头和有效载荷都是部分控制报文。
mqtt是二进制的协议,控制字段是精确到Bit级别的,单纯这一点就足觉得其在物联网领域占据一席之地。mqtt是不支持分包等机制,并不适宜一些数据包特别大的应用场景。缓存
发布者----发布消息---->代理-------推送消息----->订阅者 发布者----发布消息---->代理<------订阅消息-----订阅者
在mqtt协议中有三种身份:服务器
向订阅的客户端转发应用程序消息网络
断开服务器链接并发
# sudo yum install epel-release # sudo yum install mosquitto mosquitto-clients # sudo systemctl start mosquitto mqtt默认是以1883端口运行的
mosquitto的配置文件为/etc/mosquitto/mosquitto.conf/ 1.添加密码配置而且不容许匿名用户登陆 # sudo vim /etc/mosquitto/mosquitto.conf allow_anonymous false #不容许匿名登陆 password_file /etc/mosquitto/pwfile #配置用户密码文件 acl_file /etc/mosquitto/aclfile # 配置topic和用户 2.添加用户信息 # mosquitto_passwd -c /etc/mosquitto/pwfile ceshi # mosquitto_passwd /etc/mosquitto/pwfile ceshi2 分别添加用户ceshi和ceshi2 3.添加topic和用户的关系(权限配置) # sudo vim /etc/mosquitto/aclfile # ceshi只能发布V222为前缀的主题,订阅V333开头的主题 user ceshi topic write V222/# topic read V333/# # ceshi2只能订阅以V222为前缀的主题 user ceshi2 topic read V222/# - write:发布订阅 - read:接受订阅 4.启动 -c :指定配置文件启动 -d: 后台运行 mosquitto -c /etc/mosquitto/mosquitto.conf -d 5.测试 发布订阅:mosquitto_pub 接受订阅:mosquitto_sub 参数: -h :服务器主机 -t :指定主题 -u :用户名 -P : 密码 -i :客户端id -m :发布的消息内容 # mosquitto_sub -h localhost -t "V222" -u ceshi2 -P 123456 # mosquitto_pub -h localhost -t "V222" -m "Hello world" -u ceshi -P 123455
# 系统状态的刷新时间 # sys_interval 10 # 系统资源的回收时间,0表示尽快处理 # store_clean_interval 10 # 服务进程的pid # pid_file /var/run/mosquitto.pid # 服务进程的系统用户 # user mosquitto # 客户端心跳消息的最大并发数 # max_inflight_messages 10 # 客户端心跳消息缓存队列 # max_queued_messages 100 # 用于设置客户端长链接的过时时间,默认永不过时 # persistent_client_expiration # 服务绑定的IP地址 # bind_address # 服务绑定的端口 # port 1883 # 消息自动保存的间隔时间 # autosave_interval 1800 # 消息自动保存功能的开关 # autosave_on_changes false # 持久化功能的开关 # persistence true # 持久化DB文件 # persistence_file mosquitto.db # 持久化DB文件目录 # persistence_location /var/lib/mosquitto/ # 4种日志模式: stdout、stderr、syslog、topic # none:则表示不记录日志 log_dest none # 选择日志的级别 # log_type error # log_type warning # log_type notice # log_type information # 是否记录客户端链接信息 # connection_messages true # 是否记录日志时间 # log_timestamp true # 容许匿名用户 # allow_anonymous false # 用户/密码文件,默认格式为:user/passwd # password_file /etc/mosquitto/passwd