Exchanging RabbitMQ messages with Mosquitto

In this example, we are going to create a Java proxy that gets the messages published by the example presented in the recipe Publishing messages from Android in the background and forward them to any mobile OS as seen in the recipe Binding an app from iPhone to RabbitMQ via MQTT, using an MQTT server as follows:

Exchanging RabbitMQ messages with Mosquitto

Getting ready

You need the Paho Java library client, which you can find at http://git.eclipse.org/c/paho/org.eclipse.paho.mqtt.java.git/.

How to do it…

  1. You have to create a consumer for the amq.fanout exchange:
    String myQueue = channel.queueDeclare().getQueue();
    String myExchange = "amq.fanout";
    channel.queueBind(myQueue,myExchange,"");
  2. Create an MQTT connection with the Paho Java client:
    mqttClient = new MqttClient(MQTTip, MqttClient.generateClientId());
    mqttClient.connect();
  3. Publish the retrieved GPS messages to the MQTT server:
    mqttClient.publish("follow.me", message, 0, false); 
  4. Change the routing topic while binding the app from iPhone to RabbitMQ via MQTT:
    mosquitto_subscribe(mosq, NULL, "follow.me", 0);
    
  5. Change the server's IP while binding the app from an iPhone to RabbitMQ via MQTT, using the MQTT server IP.

How it works…

We have to create two connections, one to RabbitMQ and one to the MQTT server; follow the steps 1-3.

When the Android app sends some messages, the consumer recieves and publishes them to the Mosquitto server using mqttClient.publish("follow.me", message, 0,false);.

You need to change the topic on the iPhone app using follow.me, and you also have to change the server's IP address.

The result is as shown in the following screenshot:

How it works…

So, if the Android app is enabled, you can see the latitude and longitude in your iPhone app.

Tip

We have used the public server test.mosquitto.org. Please read the site disclaimer before using it.

There's more…

We have divided the broker's responsibility, one for the AMQP protocol and one for the MQTT protocol.

See also

You can find more information about Paho at http://www.eclipse.org/paho/. When you build the Paho Java client source, the builder creates the Java doc in your filesystem: yourbasedir/org.eclipse.paho.mqtt.java/org.eclipse.paho.client.mqttv3/build/dist/javadoc.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset