物联网消息队列协议MQTT


简介
Mqtt是一个物联网消息传输协议

mosquitto是mqtt协议的一个开源实现,http://mosquitto.org/

paho是mqtt协议的客户端实现,这里主要用paho的mqtt java客户端jar包。

http://wiki.eclipse.org/Paho

只需要在pom.xml中增加:

<dependency>
  <groupId>org.eclipse.paho</groupId>
  <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
  <version>1.0.2</version>
</dependency>

 


mosquitto可以理解为mutt协议的server端,可部署在linux及windows上

CentOS的安装过程:

参照官网文档,在yum的repo配置中增加:

[home_oojah_mqtt]
name=mqtt (CentOS_CentOS-6)
type=rpm-md
baseurl=http://download.opensuse.org/repositories/home:/oojah:/mqtt/CentOS_CentOS-6/
gpgcheck=1
gpgkey=http://download.opensuse.org/repositories/home:/oojah:/mqtt/CentOS_CentOS-6//repodata/repomd.xml.key
enabled=1

 


mosquitto的配置文件项可参考:http://blog.csdn.net/shagoo/article/details/7910598

集群部署 参照http://www.cnblogs.com/yinyi521/p/6087215.html

然后执行:
yum install mosquitto
yum install mosquitto-client

启动mosquitto服务:

mosquitto -v

 

 

mqtt java客户端实例:

package com.haibran.mqtt_demo;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttPublicSample {

public static void main(String[] args) {
// TODO Auto-generated method stub
String topic = "sensor";
String content = "Message from MqttPublishSample";
int qos = 2;
String broker = "tcp://192.168.0.20:1883";
String clientId = "JavaSample";
MemoryPersistence persistence = new MemoryPersistence();

try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
System.out.println("Connecting to broker: "+broker);
sampleClient.connect(connOpts);
System.out.println("Connected");
System.out.println("Publishing message: "+content);
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(qos);
sampleClient.publish(topic, message);
System.out.println("Message published");
sampleClient.disconnect();
System.out.println("Disconnected");
System.exit(0);
} catch(MqttException me) {
System.out.println("reason "+me.getReasonCode());
System.out.println("msg "+me.getMessage());
System.out.println("loc "+me.getLocalizedMessage());
System.out.println("cause "+me.getCause());
System.out.println("excep "+me);
me.printStackTrace();
}
}

}

 

posted @ 2017-11-03 15:02  王晓伟  阅读(2475)  评论(0编辑  收藏