mqtt windoens 搭建服务器和步伐和订阅的demo

早在1999年,IBMAndyStanford-Clark博士以及Arcom公司ArlenNipper博士发明了MQTTMessage Queuing Telemetry Transport,消息队列遥测传输)技术 [1]  。据AndyStanford-Clark博士称,MQTT将在今年和明年呈现爆炸式增长。

是一个即时通讯协议,该协议支持所有平台,几乎可以把所有联网物品和外部连接起来,被用来当做传感器和制动器(比如通过Twitter让房屋联网)的通信协议。可以通过PHPJAVAPythonCC#等系统语言来向MQTT发送相关消息。

下主要的几项特性:

1MQTT是基于二进制消息的发布/订阅编程模式的消息协议,使用发布/订阅消息模式,提供一对多的消息发布,解除应用程序耦合;

2、对负载内容屏蔽的消息传输;

3、使用 TCP/IP 提供网络连接;

4、有三种消息发布服务质量:

o        至多一次,消息发布完全依赖底层 TCP/IP 网络。会发生消息丢失或重复。这一级别可用于如下情况,环境传感器数据,丢失一次读记录无所谓,因为不久后还会有第二次发送。

o        至少一次,确保消息到达,但消息重复可能会发生。

o        只有一次,确保消息到达一次。这一级别可用于如下情况,在计费系统中,消息重复或丢失会导致不正确的结果。

5、小型传输,开销很小(固定长度的头部是 2 字节),协议交换最小化,以降低网络流量;

MQTT提供了多个层次的安全特性:

(1)   网络层:有条件可以通过拉专线或者使用VPN来连接设备与MQTT代理,以提高网络传输的安全性。

(2)   传输层:传输层使用TLS加密是确保安全的一个好手段,可以防止中间人攻击(Man-In-The-Middle Attack)。客户端证书不但可以作为设备的身份凭证,还可以用来验证设备。

(3)   应用层:MQTT还提供客户标识(Client Identifier)以及用户名密码,在应用层验证设备。

MQTT是基于TCP的,默认情况通讯并不加密。如果你需要传输敏感信息或者对设备进行反控,使用TLS几乎是必须的。打个比方,如果你在咖啡店用免费Wi-Fi上网,登录互联网金融的网站不支持HTTPS传输,那么你的账号信息多半已经在咖啡店的Wi-Fi日志里面躺着了……

TLS是非常成熟的安全协议,在握手的时候便可以创建安全连接,使得黑客无法窃听或者篡改内容了。使用TLS的时候有以下注意点:

·        尽可能使用高版本的TLS

·        验证X509证书链防止中间人攻击。

·        尽量使用有CA发布的证书。

当然,TLS会增加连接时开销,对低运算能力的设备而言是额外的负担,不过如果设备是长连接的话就会避免反复连接的开销。


1.下载mqtt  winsowns版的

地址:http://activemq.apache.org/apollo/download.html

(1)运行...\bin\apollo.cmd create mybroker

(2)运行 ...\mybroker\bin\apollo-broker.cmd run


MQTT服务器TCP连接端口:tcp://0.0.0.0:61613

后台Web管理页面:https://127.0.0.1:61681/http://127.0.0.1:61680/

进去是这样的   默认账号admin     密码是   password


这样你的服务器就搭建好了,我们来写简单的  java se 工程里面的发布和订阅  jar包:mqtt-client-0.04.jar

发布代码

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;  
import org.eclipse.paho.client.mqttv3.MqttCallback;  
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.MqttPersistenceException;  
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;  
  
/** 
 * 发送数据到mqtt服务器 
 * @author:涂有 
 * @date 2017年8月16日 下午11:15:22 
 */  
public class SendMsg {  
    private static int qos = 2; //只有一次  
    private static String broker = "tcp://127.0.0.1:61613";  //默认端口
    private static String userName = "admin";   //默认用户名
    private static String passWord = "password";    //默认密码
  
      
    //建立连接
    private static MqttClient connect(String clientId,String userName,  
            String password) throws MqttException {
        MemoryPersistence persistence = new MemoryPersistence();  
        MqttConnectOptions connOpts = new MqttConnectOptions();  
        connOpts.setCleanSession(true);  
        connOpts.setUserName(userName);  
        connOpts.setPassword(password.toCharArray());  
        connOpts.setConnectionTimeout(10);  
        connOpts.setKeepAliveInterval(20);  
        //String[] uris = {"tcp://10.100.124.206:1883","tcp://10.100.124.207:1883"};  
        //connOpts.setServerURIs(uris);  //起到负载均衡和高可用的作用  
        MqttClient mqttClient = new MqttClient(broker, clientId, persistence);
        mqttClient.setCallback(new PushCallback("test"));  
        mqttClient.connect(connOpts);  
        return mqttClient;  
    }  
  
    private static void pub(MqttClient sampleClient, String msg,String topic)   
            throws MqttPersistenceException, MqttException {  
        MqttMessage message = new MqttMessage("ertwersdfas".getBytes());  
        message.setQos(qos);  
        message.setRetained(false);  
        sampleClient.publish(topic, message);  
    }  
      
    private static void publish(String str,String clientId,String topic) throws MqttException{  
       System.out.println("laile1");
    	MqttClient mqttClient = connect(clientId,userName,passWord);  
  
        if (mqttClient != null) {  
            pub(mqttClient, str, topic);  
            System.out.println("pub-->" + str);  
        }  
  
        if (mqttClient != null) {  
            mqttClient.disconnect();  
        }  
    }  
  
    public static void main(String[] args) throws MqttException { 
    	System.out.println("liale");
        publish("message content","0","$share/edge/server/public/a");  
    }  
}  
  
class PushCallback implements MqttCallback {  
    private String threadId;  
    public PushCallback(String threadId){  
        this.threadId = threadId;  
    }  
      
    public void connectionLost(Throwable cause) {  
          
    }  
  
    public void deliveryComplete(IMqttDeliveryToken token) {  
       System.out.println("deliveryComplete---------" + token.isComplete());  
    }  
  
    public void messageArrived(String topic, MqttMessage message) throws Exception {  
        String msg = new String(message.getPayload());  
        System.out.println(threadId + " " + msg);  
    }  
}  

订阅者:

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 ConMsg {  
  
//   private static String topic = "$share/testgroup/wyptest1";  
//   private static String topic = "$queue/wyptest1";  
//   private static String topic = "wyptest1";  
     private static int qos = 2;  
     private static String broker = "tcp://127.0.0.1:61613";  
     private static String userName = "admin";  
     private static String passWord = "password";  
   
      
  
     private static MqttClient connect(String clientId) throws MqttException{  
         MemoryPersistence persistence = new MemoryPersistence();  
         MqttConnectOptions connOpts = new MqttConnectOptions();  
//       String[] uris = {"tcp://10.100.124.206:1883","tcp://10.100.124.206:1883"};  
         connOpts.setCleanSession(false);  
         connOpts.setUserName(userName);  
         connOpts.setPassword(passWord.toCharArray());  
         connOpts.setConnectionTimeout(10);  
         connOpts.setKeepAliveInterval(20);  
//         connOpts.setServerURIs(uris);  
//         connOpts.setWill(topic, "close".getBytes(), 2, true);  
         MqttClient mqttClient = new MqttClient(broker, clientId, persistence);  
         mqttClient.connect(connOpts);  
         return mqttClient;  
     }  
       
     public static void sub(MqttClient mqttClient,String topic) throws MqttException{  
         int[] Qos  = {qos};  
         String[] topics = {topic};  
         mqttClient.subscribe(topics, Qos);  
     }  
       
       
    private static void runsub(String clientId, String topic) throws MqttException{  
        MqttClient mqttClient = connect(clientId);  
        if(mqttClient != null){  
            sub(mqttClient,topic);  
        }  
    }  
    public static void main(String[] args) throws MqttException{  
          
        runsub("0", "$share/edge/server/public/a");  
    }  
}  

(2)springboot监听topic接受数据

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.handler.LoggingHandler;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

import com.sgcc.iot.product.application.exception.MyException;
import com.sgcc.iot.product.application.service.ThingService;



/**
 * MQTT监听启动类
 * @author wangbin
 *
 */
@SpringBootConfiguration
public class MqttInbound {
	
	@Autowired
	ThingService thingService;
	

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Value("${mqtt.broker.serverUri}")
    private String serviceUri ;

    @Value("${mqtt.broker.username:}")
    private String username ;

    @Value("${mqtt.broker.password:}")
    private String password ;

    @Value("${mqtt.inboundclientId}")
    private String clientId ;
    
    @Value("${mqtt.qos}")
    private int qos = 1;
    
    @Value("${mqtt.completionTimeout}")
    private int completionTimeout ;
    
    private static String ONLINE = "online";
    
	
    /**
     * mqtt的通道
     * @return
     */
	@Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }
/**
 * 创建mqtt的连接工厂
 * @return
 */
	@Bean
	public MqttPahoClientFactory mqttClientFactory() {
		DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
		factory.setServerURIs(serviceUri);
		factory.setUserName(username);
		factory.setPassword(password);
		//factory.setKeepAliveInterval(20);
		factory.setCleanSession(false);
		return factory;
	}
	
	
/**
 * 监听的topic
 * @return
 */
	@Bean
    public MessageProducer inbound() {
		logger.info("====clientId==="+clientId);
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(clientId, mqttClientFactory(),
                		  "$iot/thingGrid/offline","$iot/thingGrid/online");
        adapter.setCompletionTimeout(completionTimeout);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(qos);
        adapter.setOutputChannel(mqttInputChannel());
        logger.info("====clientId==="+"连接了");
        return adapter;
    }
	
	
	/**
	 * 通过监听从通道获取数据
	 * @return
	 */
	
	@Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return new MessageHandler() {

            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
            	String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
            	String type = topic.substring(topic.lastIndexOf("/")+1, topic.length());
				logger.info(type);
				logger.info(message.getPayload().toString());
				
				if(message.getPayload()==null){
					try {
						throw new MyException("422","EXCEPTION");
					} catch (MyException e) {
						e.printStackTrace();
					}
				}
				
            	if(ONLINE.equals(type)){
            		try {
						thingService.updateOnlineLineFlag(message.getPayload().toString());
					} catch (MyException e) {
						logger.error(e.getMessage());
						e.printStackTrace();
					}
            	}else{
            		try {
						thingService.updateOfflineLineFlag(message.getPayload().toString());
					} catch (MyException e) {
						logger.error(e.getMessage());
						e.printStackTrace();
					}
            	}
				
            }

        };
    }

}

yml中的配置

mqtt:
  broker:
    serverUri: tcp://127.0.0.1:61613
    username: admin
    password: password
  inboundclientId: 0
  qos: 2
  completionTimeout: 5000

jar包:

compile('org.springframework.integration:spring-integration-mqtt')
compile('org.springframework.integration:spring-integration-core')


阅读更多
个人分类: mqtt 后台
上一篇ribbitMq生产者和Springboot 动态监听ribbitMq消费者
下一篇springboot 集成 WebScoket
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭