以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協議規範的文章

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章