是什么
MQTT(遥感传输)是由IBM的Andy Stanford-Clark博士和Arcom(现在的Eurotech)的Arlen Nipper在1999年发明的。是一个机器对机器(M2M)/“物联网”连接协议,设计为一种非常轻量级的发布/订阅消息传输。
MQTT的默认端口号是1833,官网的原文是这样子的:
Are there standard ports for MQTT to use?
Yes. TCP/IP port 1883 is reserved with IANA for use with MQTT. TCP/IP port 8883 is also registered, for using MQTT over SSL.
设计原则
最小化网络带宽和设备资源需求,同时试图确保可靠性和一定程度的交付保证
应用场景
一般适用于需要少量代码占用和/或网络带宽昂贵的远程位置的连接。专门为为受限设备和低带宽、高延迟或不可靠的网络设计
- 通过卫星链路与代理通信的传感器
- 通过与医疗服务提供商的偶尔拨号连接的传感器
- 家庭自动化和小型设备场景
- 它也是移动应用程序的理想选择,因为它体积小、功耗低、数据包最少,并且可以有效地将信息分发给一个或多个接收者
怎么用
运行环境: ubuntu18
使用:mosquitto
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa #添加源到软件仓库
sudo apt-get update #更新软件仓库列表
sudo apt-get install mosquitto #安装mosquitto
sudo service mosquitto status #查看运行状态
sudo service mosquitto start #启动服务 还可以用mosquitto -v
sudo service mosquitto stop #停止服务
运行成功状态截图
添加和修改配置
首先停止服务
service mosquitto stop
cd etc/mosquitto/conf.d/,新建myconfig.conf,输入一下内容
# 关闭匿名访问,客户端必须使用用户名
allow_anonymous false
#指定 用户名-密码 文件
password_file /etc/mosquitto/pwfile.txt
假如用户名为user1
运行,输入密码123456
mosquitto_passwd -c /etc/mosquitto/pwfile.txt user1 # -c 创建一个用户、/etc/mosquitto/pwfile.txt 是将用户创建到 pwfile.txt 文件中、user1是用户名。
查看是否存在他的进程
ps -aux|grep mosquitto
效果如下:
#订阅主题
mosquitto_sub -h 192.168.1.102 -t "mqtt" -v
#发布主题
mosquitto_pub -h 192.168.1.102 -t "mqtt" -m "Hello Stonegeek"
MQTT 整合SpringBoot
代码已经已经提交到github ,地址 https://github.com/TanHA19/SpringBootAndMqtt.git