Example usage for com.rabbitmq.client Channel exchangeDeclare

List of usage examples for com.rabbitmq.client Channel exchangeDeclare

Introduction

In this page you can find the example usage for com.rabbitmq.client Channel exchangeDeclare.

Prototype

Exchange.DeclareOk exchangeDeclare(String exchange, BuiltinExchangeType type) throws IOException;

Source Link

Document

Actively declare a non-autodelete, non-durable exchange with no extra arguments

Usage

From source file:org.wso2.carbon.caching.invalidator.amqp.CacheInvalidationPublisher.java

License:Open Source License

@Override
public void invalidateCache(int tenantId, String cacheManagerName, String cacheName, Serializable cacheKey) {
    log.debug("Global cache invalidation: initializing the connection");
    if (ConfigurationManager.getProviderUrl() == null) {
        ConfigurationManager.init();/*from www .jav a  2 s  .c  o  m*/
    }
    //Converting data to json string
    GlobalCacheInvalidationEvent event = new GlobalCacheInvalidationEvent();
    event.setTenantId(tenantId);
    event.setCacheManagerName(cacheManagerName);
    event.setCacheName(cacheName);
    event.setCacheKey(cacheKey);
    String uuid = UUIDGenerator.generateUUID();
    event.setUuid(uuid);
    // Setup the pub/sub connection, session
    // Send the msg (byte stream)
    Connection connection = null;
    try {
        log.debug("Global cache invalidation: converting serializable object to byte stream.");
        byte data[] = serialize(event);
        log.debug("Global cache invalidation: converting data to byte stream complete.");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ConfigurationManager.getProviderUrl());
        connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(ConfigurationManager.getTopicName(), "topic");
        channel.basicPublish(ConfigurationManager.getTopicName(), "invalidate.cache", null, data);
        ConfigurationManager.getSentMsgBuffer().add(uuid.trim());
        log.debug("Global cache invalidation message sent: " + new String(data));
    } catch (Exception e) {
        log.error("Global cache invalidation: Error publishing the message", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                log.error("Global cache invalidation: error close publish connection", e);
            }
        }
    }
}

From source file:org.wso2.carbon.caching.invalidator.amqp.CacheInvalidationSubscriber.java

License:Open Source License

private void subscribe() {
    log.debug("Global cache invalidation: initializing the subscription");
    try {//from w ww  . java2  s  .com
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ConfigurationManager.getProviderUrl());
        int port = Integer.parseInt(ConfigurationManager.getProviderPort());
        factory.setPort(port);
        factory.setUsername(ConfigurationManager.getProviderUsername());
        factory.setPassword(ConfigurationManager.getProviderPassword());
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(ConfigurationManager.getTopicName(), "topic");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, ConfigurationManager.getTopicName(), "#");
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);
        Thread reciever = new Thread(messageReciever);
        reciever.start();
        log.info("Global cache invalidation is online");
    } catch (Exception e) {
        log.error("Global cache invalidation: Error message broker initialization", e);
    }
}

From source file:pl.nask.hsn2.bus.rabbitmq.RbtUtils.java

License:Open Source License

/**
 * Creates exchanges and static bindings between them.
 * //from w  ww.ja va2 s  .  co m
 * @param connection Connection to Rabbit MQ server.
 * @param exchangeCommonName Common exchange name.
 * @param exchangeServicesName Services exchange name.
 * @param exchangeMonitoringName Monitoring exchange name.
 * @throws BusException Any problem with connection or queue will thrown an exception.
 */
public static void createExchanges(Connection connection, String exchangeCommonName,
        String exchangeServicesName, String exchangeMonitoringName) throws BusException {
    Channel channel = createChannel(connection);
    try {
        channel.exchangeDeclare(exchangeCommonName, "fanout");
        channel.exchangeDeclare(exchangeMonitoringName, "fanout");
        channel.exchangeDeclare(exchangeServicesName, "direct");
        channel.exchangeBind(exchangeMonitoringName, exchangeCommonName, "");
        channel.exchangeBind(exchangeServicesName, exchangeCommonName, "");
    } catch (IOException ex) {
        throw new BusException(ex);
    } finally {
        closeChannel(channel);
    }
}

From source file:pl.nask.hsn2.DataStoreActiveCleaner.java

License:Open Source License

/**
 * Initialize RabbitMQ connection./*  www.  j  a v a2s  .c om*/
 *
 * @return RabbitMQ consumer.
 * @throws IOException
 *             When there's some connection issues.
 */
private QueueingConsumer initRabbitMqConnection() throws IOException {
    ConnectionFactory connFactory = new ConnectionFactory();
    connFactory.setHost(rbtHostName);
    rbtConnection = connFactory.newConnection();
    Channel channel = rbtConnection.createChannel();
    channel.exchangeDeclare(rbtNotifyExchName, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, rbtNotifyExchName, "");
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, AUTO_ACK, consumer);
    return consumer;
}

From source file:pro.foundev.examples.spark_streaming.java.interactive.querybasedconsumer.ResponseWriter.java

License:Apache License

private Messenger initRabbitMqResponseQueue() {

    ConnectionFactory factory = new ConnectionFactory();
    final Connection connection;
    final Channel channel;
    factory.setHost("localhost");
    try {/*from  w  ww.  ja v  a2  s . co  m*/
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            ResponseWriter.mainThread.interrupt();
            try {
                channel.close();
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    return new MessengerImpl(channel);
}

From source file:pro.foundev.examples.spark_streaming.java.messaging.RabbitMQEmitWarnings.java

License:Apache License

public static void main(String[] argv) throws java.io.IOException {
    String master = Args.parseMaster(argv);

    mainThread = Thread.currentThread();

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(master);/*  w ww .  j a va  2s .  c  o m*/
    final Connection connection = factory.newConnection();
    final Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            RabbitMQEmitWarnings.mainThread.interrupt();
            try {
                channel.close();
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    while (true) {
        String message = buildMessage();
        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

From source file:pt.ua.ies.ControllerView.java

@PostConstruct
public void init() {
    System.out.println("init");
    recive = "";/*  w  w w  . ja v a  2  s .co  m*/
    reciveBeforeRefresh = recive;
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(DisplayMessage.EXCHANGE_NAME, "fanout");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, DisplayMessage.EXCHANGE_NAME, "");

        MessageConsumer m = new MessageConsumer(channel, this);

        channel.basicConsume(queueName, true, m);
    } catch (Exception ex) {
        Logger.getLogger(ControllerView.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:pt.ua.ies.Main.java

public static void main(String[] args) {
    try {//from w  w w.java2 s. c  o m
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

        String message = "Random Message " + new Random().nextInt(1000);
        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");

        /**
         * Close the channel and the connection
         */
        channel.close();
        connection.close();
    } catch (Exception ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:pubsub.RecieveLogs.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, "");

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override/*from w w w .  j a v  a 2  s  . c o  m*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:rabbitirc.RabbitIRC.java

public static void main(String[] argv) throws java.io.IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Random rnd = new Random();
    int indeks = rnd.nextInt(usernamelist.length);
    String Randusername = usernamelist[indeks] + rnd.nextInt(100);

    user = Randusername;//ww  w  .  j  a  va  2s  . c o  m
    channellist.add("lounge");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    String queueName = channel.queueDeclare().getQueue();
    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    Scanner sc = new Scanner(System.in);

    channel.queueBind(queueName, EXCHANGE_NAME, "lounge");
    channellist.add("lounge");
    Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received :'" + message + "'");
        }
    };
    System.out.println(" Welcome " + user + " to Channel lounge");
    System.out.println(" Queries: ");
    System.out.println(" 1. /NICK <Username>            : Change username ");
    System.out.println(" 2. /JOIN <Channel Name>        : Join Channel");
    System.out.println(" 3. @<Channel Name> <Message>   : Send message to Spesific Channel");
    System.out.println(" 4. /LEAVE <Channel Name>       : Leave Channel");
    System.out.println(" 5. <Random text>               : BroadCast");
    System.out.println(" 6. /EXIT                       : Exit App");
    while (true) {
        channel.basicConsume(queueName, true, consumer);
        String input = sc.nextLine();
        String[] query;
        if ((query = CommandRegexes.NICK.match(input)) != null) {
            String Nickname = query[0];
            user = Nickname;
            System.out.println(" [x] Your Nickname '" + Nickname + "'");

        } else if ((query = CommandRegexes.JOIN.match(input)) != null) {
            String channel_name = query[0];
            channel.queueBind(queueName, EXCHANGE_NAME, channel_name);
            channellist.add(channel_name);
            System.out.println(" [x] you had Join '" + channel_name + "'");

        } else if ((query = CommandRegexes.LEAVE.match(input)) != null) {
            String channel_name = query[0];
            if (channellist.contains(channel_name)) {
                channellist.remove(channellist.indexOf(channel_name));
                channel.queueUnbind(queueName, EXCHANGE_NAME, channel_name);
                System.out.println(" [x] you had leave '" + channel_name);
            } else {
                System.out.println(" [x] you're not in the channel " + channel_name);
            }
            System.out.println(" [x] you had leave '" + channel_name + "'");

        } else if (CommandRegexes.EXIT.match(input) != null) {
            channel.close();
            connection.close();
            break;

        } else if ((query = CommandRegexes.MESSAGE_CHANNEL.match(input)) != null) {
            String channel_name = query[0];
            if (channellist.contains(channel_name)) {
                String message = "[" + channel_name + "] (" + user + ") " + query[1];
                channel.basicPublish(EXCHANGE_NAME, channel_name, null, message.getBytes());
                System.out.println(" [x] Sent '" + message + "'");
                System.out.println(" : to '" + channel_name + "'");
            } else {
                System.out.println(" [x] No Channel " + channel_name + " on your list");
            }
        } else {
            System.out.println(" [x] Broadcasting '" + input + "'");
            for (String channellist1 : channellist) {
                String messages = "[" + channellist1 + "] (" + user + ") " + input;
                channel.basicPublish(EXCHANGE_NAME, channellist1, null, messages.getBytes());
            }
            System.out.println(" [x] OK ;D");
        }
    }

}