以Apollo服务器作为中间件,模拟MQTT客户端,MQTT订阅接受消息

一、Windows下安装Apollo
下载链接:http://activemq.apache.org/apollo/download.html
解压至C:\ 根目录下(可自选)本文以C盘根目录为例
二、创建apollo实例,如图操作:
打开cmd,编辑命令 
三、启动apollo实例(cmd命令切换至刚创建的实例目录下的bin目录下敲入 apollo-broker run),如下图可看到apollo的启动情况

可进入http://localhost:61680 查看apollo后台(登录名默认为admin 密码为password)
四、创建模拟发送消息的客户端,代码如下
package com.vin.foo;

import org.fusesource.hawtbuf.Buffer;
import org.fusesource.hawtbuf.UTF8Buffer;
import org.fusesource.mqtt.client.FutureConnection;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.QoS;

public class MQTTClient {

	public static void main(String[] args) throws Exception {
		sendMessage("hello");
	}
	public static void sendMessage(String message) {
		String user = env("APOLLO_USER", "admin");
		String password = env("APOLLO_PASSWORD", "password");
		String host = env("APOLLO_HOST", "localhost");//apollo服务器地址
		int port = 61613;//apollo端口号
		String destination = "/topic/1/OOOOOOOOOO/aaaa";//topic
		Buffer msg = new UTF8Buffer(message);
		MQTT mqtt = new MQTT();//新建MQTT
		try {
			mqtt.setHost(host, port);
			mqtt.setUserName(user);
			mqtt.setPassword(password);

			FutureConnection connection = mqtt.futureConnection();
			connection.connect().await();
			UTF8Buffer topic = new UTF8Buffer(destination);
			connection.publish(topic, msg, QoS.AT_LEAST_ONCE, false);
			connection.disconnect().await();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// System.exit(0);
		}
	}

	private static String env(String key, String defaultValue) {
		String rc = System.getenv(key);
		if (rc == null) {
			return defaultValue;
		}
		return rc;
	}

}
	</span>
五、创建接受消息的订阅者</span>
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more  
 */
package com.vin.foo;

import org.fusesource.hawtbuf.Buffer;
import org.fusesource.hawtbuf.UTF8Buffer;
import org.fusesource.mqtt.client.Callback;
import org.fusesource.mqtt.client.CallbackConnection;
import org.fusesource.mqtt.client.Listener;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;

/**
 * Uses an callback based interface to MQTT. Callback based interfaces are
 * harder to use but are slightly more efficient.
 */
class MQTTListener {

	public static void main(String[] args) throws Exception {

		String user = env("APOLLO_USER", "admin");
		String password = env("APOLLO_PASSWORD", "password");
		String host = env("APOLLO_HOST", "localhost");
		int port = Integer.parseInt(env("APOLLO_PORT", "61613"));
		final String destination = arg(args, 0, "/topic/1/OOOOOOOOOO/aaaa");

		MQTT mqtt = new MQTT();
		mqtt.setHost(host, port);
		mqtt.setUserName(user);
		mqtt.setPassword(password);
		mqtt.setKeepAlive((short) 30);
		// mqtt.setCleanSession(false);
		// mqtt.setClientId("aaaa");

		final CallbackConnection connection = mqtt.callbackConnection();

		connection.listener(new Listener() {
			public void onConnected() {
			}

			public void onDisconnected() {
			}

			public void onFailure(Throwable value) {
				value.printStackTrace();
				System.exit(-2);
			}

			public void onPublish(UTF8Buffer topic, Buffer msg, Runnable ack) {
				String body = msg.utf8().toString();
				System.out.println(body);
				ack.run();
			}
		});
		connection.connect(new Callback<Void>() {
			@Override
			public void onSuccess(Void value) {
				Topic[] topics = { new Topic(destination, QoS.AT_LEAST_ONCE) };
				connection.subscribe(topics, new Callback<byte[]>() {
					public void onSuccess(byte[] qoses) {
						System.out.println("connected...");
					}

					public void onFailure(Throwable value) {
						value.printStackTrace();
						System.exit(-2);
					}
				});
			}

			@Override
			public void onFailure(Throwable value) {
				value.printStackTrace();
				System.exit(-2);
			}
		});
		// Wait forever..
		synchronized (MQTTListener.class) {
			while (true) {
				MQTTListener.class.wait();
			}
		}
	}

	private static String env(String key, String defaultValue) {
		String rc = System.getenv(key);
		if (rc == null) {
			return defaultValue;
		}
		return rc;
	}

	private static String arg(String[] args, int index, String defaultValue) {
		if (index < args.length) {
			return args[index];
		} else {
			return defaultValue;
		}
	}
}
</pre><pre name="code" class="java">六、运行MQTTListener,可建立一个topic长连接/topic/1/OOOOOOOOOO/aaaa,运行MQTTClient可向订阅者/topic/1/OOOOOOOOOO/aaaa发送一个“hello”消息。可在后台查看连接状态,也可在java控制台看到接受的消息。</span>
代码中具体各参数的定义请参考我上一篇转载MQTT协议规范的文章

展开阅读全文

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