MQTT(Message Queuing Telemetry Transport)는 경량 발행-구독 메시징 프로토콜로, IoT 디바이스 간 통신에 최적화됐다. OASIS 표준(v5.0)이며 TCP/IP 기반이다.
MQTT QoS 레벨
| QoS | 이름 | 전달 보장 | 중복 가능 | 용도 |
|---|
| 0 | At most once | 최대 1회 | 없음 | 센서 스트리밍 |
| 1 | At least once | 최소 1회 | 가능 | 알림 |
| 2 | Exactly once | 정확히 1회 | 없음 | 결제, 중요 명령 |
QoS 2 핸드셰이크
Publisher Broker Subscriber
│── PUBLISH ──>│ │
│ QoS=2 │── PUBLISH ──────────>│
│<── PUBREC ───│<── PUBREC ───────────│
│── PUBREL ──>│── PUBREL ────────────>│
│<── PUBCOMP ──│<── PUBCOMP ──────────│
4번 교환으로 정확히 1회 전달 보장
MQTT 5.0 새 기능
python
import asyncio
from aiomqtt import Client
async def mqtt_v5_demo():
async with Client("broker.hivemq.com", port=1883) as client:
# 공유 구독 (로드 밸런싱)
await client.subscribe("$share/mygroup/sensors/#", qos=1)
# 메시지 발행 (만료 시간, 응답 토픽, 사용자 속성)
await client.publish(
"factory/temp",
payload=b"72.5",
qos=1,
properties={
"MessageExpiryInterval": 300, # 5분 후 만료
"ResponseTopic": "factory/temp/response",
"CorrelationData": b"req-001",
"UserProperty": [("unit", "celsius"), ("sensor", "DHT22")]
}
)
async for message in client.messages:
print(f"Topic: {message.topic}, Payload: {message.payload}")
asyncio.run(mqtt_v5_demo())
브로커 비교
| 브로커 | 최대 연결 | 클러스터 | 영속성 | 특징 |
|---|
| Mosquitto | ~100K | 없음 | 파일 | 경량, 임베디드 |
| EMQX | 수백만 | 있음 | 있음 | 엔터프라이즈 |
| HiveMQ | 수백만 | 있음 | 있음 | 클라우드 네이티브 |
| VerneMQ | 수십만 | 있음 | 있음 | Erlang 기반 |
Mosquitto 설정
conf
# /etc/mosquitto/mosquitto.conf
listener 1883
allow_anonymous false
password_file /etc/mosquitto/passwd
listener 8883
cafile /etc/mosquitto/certs/ca.crt
certfile /etc/mosquitto/certs/server.crt
keyfile /etc/mosquitto/certs/server.key
tls_version tlsv1.3
persistence true
persistence_location /var/lib/mosquitto/
관련 문서