MQTT(Message Queue Telemetry Transport,即消息隊列遙測傳輸協議)是一種輕量級的消息傳輸協議,主要用于物聯網設備或低帶寬網絡環境下的通信。MQTT協議中包含三個主要組件:客戶端、消息代理(Broker)和訂閱(Subscription)。
AMQP(Advanced Message Queuing Protocol,即高級消息隊列協議)是一種傳輸協議,主要用于分布式消息傳輸。AMQP協議定義了一套消息格式以及客戶端與Broker之間的通信規則,支持多語言和多平臺的使用。
//MQTT示例代碼 MqttClient client = new MqttClient(brokerUrl, clientId); MqttConnectOptions connOpt = new MqttConnectOptions(); connOpt.setCleanSession(true); client.connect(connOpt); //發布消息 MqttMessage message = new MqttMessage(content.getBytes()); message.setQos(qos); client.publish(topic, message); //訂閱消息 client.subscribe(topic); client.setCallback(new MqttCallback() { public void connectionLost(Throwable cause) { } public void messageArrived(String topic, MqttMessage message) throws Exception { //處理接收到的消息 } public void deliveryComplete(IMqttDeliveryToken token) { } });
//AMQP示例代碼 ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost(hostName); Connection connection = connectionFactory.newConnection(); //創建通道 Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, "direct"); //發送消息 channel.basicPublish(exchangeName, routingKey, null, message.getBytes()); //接收消息 channel.queueDeclare(queueName, false, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); channel.basicConsume(queueName, new DefaultConsumer(channel) { public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); //處理接收到的消息 } });