基于apollo的mqtt实现(java)

版权声明:本文为博主原创文章,转载请注明原文地址。如果觉得对您有帮助的话,请点个赞!如果想踩一脚的话,至少评论下哪里不足或者让您不满意,谢谢! https://blog.csdn.net/qq_34309305/article/details/70050096

最近项目中有要研究mqtt的需求,所以网上查看了资料,学习了基于apollo服务器的mqtt实现。

下载apollo服务器后,它自带了一个example,我这里根据我的需求给他改变了一下。

做成了一个可以1对多实时通信的例子。

总客户端代码:

package main.java.example;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.fusesource.hawtbuf.AsciiBuffer;
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.Future;
import org.fusesource.mqtt.client.FutureConnection;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;

/**
 * Uses a Future based API to MQTT.
 */
class Publisher {

	static List<String> aArray = new ArrayList<String>();
	static Boolean stachange = false;
	static String DATA = null;
	static String DATAtemp = null;	
	static MQTT mqtt = new MQTT();

	public static void main(final 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 destinationL = arg(args, 0, "/topic/+");		

		mqtt.setHost(host, port);
		mqtt.setUserName(user);
		mqtt.setPassword(password);
		
		mqtt.setWillRetain(true);
		mqtt.setWillTopic("/chart/user1");
		mqtt.setWillMessage("总部掉线le ");
		// ------------------------------------------------------------listener-------------------------------------------------------------------------------------------

		final CallbackConnection connectionL = mqtt.callbackConnection();
		connectionL.listener(new org.fusesource.mqtt.client.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 usertopic = topic.toString().substring(6);

				String body = msg.utf8().toString();
				if (body.length() > 6) {
					if (body.substring(0, 6).toString().equals("topic:")) {
						aArray.add(body.substring(6));
						System.out.println(usertopic + " join in!");
						System.out.println("talk started!");
						stachange = true;

					}
					else {
						System.out.println(usertopic + ":" + body);
					}
				}
				else {
					System.out.println(usertopic + ":" + body);
				}

			}
		});
		
		connectionL.connect(new Callback<Void>() {
			@Override
			public void onSuccess(Void value) {
				Topic[] topics = {new Topic(destinationL, QoS.AT_LEAST_ONCE)};
				connectionL.subscribe(topics, new Callback<byte[]>() {
					public void onSuccess(byte[] qoses) {
					}

					public void onFailure(Throwable value) {
						value.printStackTrace();
					}
				});
			}

			@Override
			public void onFailure(Throwable value) {
				value.printStackTrace();
			}
		});

//----------------------------------------------------------------listener end-----------------------------------------------------------------------------------------
		final Timer t = new Timer();
		t.schedule(new TimerTask() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (aArray.size() != 0 && stachange) {
					try {
						stachange = false;
						startTalk(mqtt, args);

					}
					catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
// t.cancel();
				}

			}

		}, 0, 1000);

// connection.disconnect().await();

// System.exit(0);

	}

	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;
	}

	private static void startTalk(MQTT mqtt ,String[] args) throws Exception {
		if (aArray.size() > 0) {	
				
				while (!stachange && (DATA == null || !"end".equals(DATA.toString()))) {
					DATAtemp = DATA;
					java.util.Scanner input = new java.util.Scanner(System.in);

					DATA = input.next();

					if (DATAtemp != DATA) {
						System.out.println("lilei SAY:" + DATA);
						Buffer msg = new AsciiBuffer(DATA);
						for (int i = 0; i < aArray.size(); i++) {
							
							String topicsString = aArray.get(i);
							final String destinationP = arg(args, 0, topicsString);
						
							FutureConnection connection = mqtt.futureConnection();
							connection.connect().await();				

							final LinkedList<Future<Void>> queue = new LinkedList<Future<Void>>();
							UTF8Buffer topic = new UTF8Buffer(destinationP);

							// Send the publish without waiting for it to complete. This allows us
							// to send multiple message without blocking..
							queue.add(connection.publish(topic, msg, QoS.AT_LEAST_ONCE, true));
							// Eventually we start waiting for old publish futures to complete
							// so that we don't create a large in memory buffer of outgoing message.s
							if (queue.size() >= 1000) {
									queue.removeFirst().await();					
							}
		
//							while (!queue.isEmpty()) {							
//									queue.removeFirst().await();							
//							}
						}
					}

			}
		}

	}

}
接下来是分部的代码:

package main.java.example;

import java.util.LinkedList;

import org.fusesource.hawtbuf.AsciiBuffer;
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.Future;
import org.fusesource.mqtt.client.FutureConnection;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;

/**
 * Uses a Future based API to MQTT.
 */
class client {

	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", "172.26.111.111");
		int port = Integer.parseInt(env("APOLLO_PORT", "61613"));
		final String destination = arg(args, 0, "/topic/user2");
		final String destinationL = arg(args, 0, "/chart/user1");
		String DATA = null;
		String DATAtemp = null;

		MQTT mqtt = new MQTT();
		mqtt.setHost(host, port);
		mqtt.setUserName(user);
		mqtt.setPassword(password);

		// ------------------------------------------------------------listener-------------------------------------------------------------------------------------------

		final CallbackConnection connectionL = mqtt.callbackConnection();
		connectionL.listener(new org.fusesource.mqtt.client.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);

			}
		});
		connectionL.connect(new Callback<Void>() {
			@Override
			public void onSuccess(Void value) {
				Topic[] topics = {new Topic(destinationL, QoS.AT_LEAST_ONCE)};
				connectionL.subscribe(topics, new Callback<byte[]>() {
					public void onSuccess(byte[] qoses) {
					}

					public void onFailure(Throwable value) {
						value.printStackTrace();
					}
				});
			}

			@Override
			public void onFailure(Throwable value) {
				value.printStackTrace();
			}
		});

		// ----------------------------------------------------------------listener end---------------------------------------------------------------------

		while (DATA == null || !"end".equals(DATA.toString())) {
			DATAtemp = DATA;
			java.util.Scanner input = new java.util.Scanner(System.in);

			DATA = input.next();

			if (DATAtemp != DATA) {
				System.out.println("I SAY:" + DATA);
				Buffer msg = new AsciiBuffer(DATA);

				FutureConnection connection = mqtt.futureConnection();
				connection.connect().await();

				final LinkedList<Future<Void>> queue = new LinkedList<Future<Void>>();
				UTF8Buffer topic = new UTF8Buffer(destination);

				// Send the publish without waiting for it to complete. This allows us
				// to send multiple message without blocking..
				queue.add(connection.publish(topic, msg, QoS.AT_LEAST_ONCE, false));

				// Eventually we start waiting for old publish futures to complete
				// so that we don't create a large in memory buffer of outgoing message.s
				if (queue.size() >= 1000) {
					queue.removeFirst().await();
				}

				while (!queue.isEmpty()) {
					queue.removeFirst().await();
				}

			}

		}

// connection.disconnect().await();

// System.exit(0);

	}

	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;
	}

}
通讯时,分部先把自己的主题发送给总部:topic:/chart/user1

然后两个人就可以通信了。实时的哦!拜了个拜!^_^


阅读更多
换一批

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