raspisensormodule.BrokerSubscriber.java Source code

Java tutorial

Introduction

Here is the source code for raspisensormodule.BrokerSubscriber.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package raspisensormodule;

import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 *
 * @author thor
 */
public class BrokerSubscriber {

    public static final String SENSOR_EXCHANGE = "sensorExchange";
    public static final String CONTROLER_EXCHANGE = "controllerExchange";
    public static final String BIND_KEY_ALL_SENSOR = "sensor.#";

    boolean autoAck = false;
    Channel sensorChannel;

    DefaultConsumer sensorConsumer = new DefaultConsumer(sensorChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            //            String routingKey = envelope.getRoutingKey();
            //            String contentType = properties.getContentType();
            //            long deliveryTag = envelope.getDeliveryTag();
            String message = new String(body, "UTF-8");
            System.out.println(" --> Received '" + envelope.getRoutingKey() + "':'" + message + "'");

        }
    };

    int foo;

    public BrokerSubscriber() {
        this.foo = 1;

        try {

            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            Connection connection = factory.newConnection();
            sensorChannel = connection.createChannel();

            sensorChannel.exchangeDeclare(SENSOR_EXCHANGE, "topic");

            String sensChName = sensorChannel.queueDeclare().getQueue();
            sensorChannel.queueBind(sensChName, SENSOR_EXCHANGE, BIND_KEY_ALL_SENSOR);
            sensorChannel.basicConsume(sensChName, true, sensorConsumer);
            System.out.println("Subscriber up");

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}