Example usage for com.rabbitmq.client ConnectionFactory setHost

List of usage examples for com.rabbitmq.client ConnectionFactory setHost

Introduction

In this page you can find the example usage for com.rabbitmq.client ConnectionFactory setHost.

Prototype

public void setHost(String host) 

Source Link

Usage

From source file:com.gdp.rabbitmq.task.consumer.ext.ManualAckConsumer.java

public ManualAckConsumer() throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.1");
    Connection connection = factory.newConnection();
    channel = connection.createChannel();
}

From source file:com.gdp.rabbitmq.task.publsher.ext.HandshakePublisher.java

public HandshakePublisher() throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.1");
    connection = factory.newConnection();
    channel = connection.createChannel();
    persistence = true;/*from   w  w w .j a  v a2 s.c om*/
}

From source file:com.gdp.rabbitmq.task.publsher.ext.HandshakePublisher.java

@Override
protected void execute() {
    try {//from   w ww .j  a v  a  2 s  . co  m
        channel.confirmSelect();
        publish(Utility.GenerateRandomTask());
        channel.waitForConfirmsOrDie();
        channel.close();
        connection.close();
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        connection = factory.newConnection();
        channel = connection.createChannel();
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
    } catch (InterruptedException ex) {
        Logger.getLogger(HandshakePublisher.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.gemini.provision.network.main.GeminiNetworkProvisionMain.java

public static void main(String[] args) {

    //activate logging level if it is DEBUG, default is INFO so no need for any
    //action if it is otherwise
    Injector propInjector = Guice.createInjector(new GeminiPropertiesModule());
    GeminiProperties properties = propInjector.getInstance(GeminiProperties.class);
    if (properties.getProperties().getProperty("LOGGING_LEVEL").equals("DEBUG")) {
        Configurator.defaultConfig().level(Level.DEBUG).activate();
    }//from   ww  w. j a v a  2  s. c  om

    //inject the mapper as it will be used in all the threads
    Injector mapperInjector = Guice.createInjector(new GeminiMapperModule());
    mapper = mapperInjector.getInstance(GeminiMapper.class);

    //the app.yml to deployment.yml converter
    Thread yamlConverterThread = new Thread(() -> {
        //setup the message receiver
        final Connection connection;
        final Channel channel;
        final QueueingConsumer consumer;

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
        String queueName = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
            queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                    properties.getProperties().getProperty("YAML_MAPPER_TOPIC"));
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException | NullPointerException | NumberFormatException ex) {
            Logger.error("Fatal Error: YAML Mapper - could not connect to messaging system. Exception: {}", ex);
            return;
        }

        QueueingConsumer.Delivery delivery = null;
        while (true) {
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
                Logger.error("Fatal Error: YAML Mapper - could not retrieve message. Exception: {}", ex);
                continue;
            }

            String routingKey = delivery.getEnvelope().getRoutingKey();
            String jsonBody = new String(delivery.getBody());

            //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE
            Integer status = 0;
            if (routingKey.equals(properties.getProperties().getProperty("YAML_MAPPER_MAP_APP"))) {
                status = mapApptoDeployment(jsonBody);
            } else {
                continue;
            }

            if (status == 0) {
                try {
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                } catch (IOException ex) {
                    Logger.error("Could not ack message. Exception: {}", ex);
                }
            } else {
                //failed so requeue the message
                try {
                    channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
                } catch (IOException ex) {
                    Logger.error("Could not nack message. Exception: {}", ex);
                }
            }
        }
    });
    yamlConverterThread.start();

    //the networking message recevier
    Thread networkingThread = new Thread(() -> {
        //setup the message receiver
        final Connection connection;
        final Channel channel;
        final QueueingConsumer consumer;

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
        String queueName = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
            queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                    properties.getProperties().getProperty("NETWORK_TOPIC"));
            //                channel.basicQos(Integer.parseUnsignedInt(properties.getProperties().getProperty("PREFETCH_COUNT")));
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException | NullPointerException | NumberFormatException ex) {
            Logger.error("Fatal Error: could not connect to messaging system. Exception: {}", ex);
            return;
        }

        QueueingConsumer.Delivery delivery = null;
        while (true) {
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
                Logger.error("Could not get message from queue. Exception: {}", ex);

                //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE
                continue;
            }

            String routingKey = delivery.getEnvelope().getRoutingKey();
            String jsonBody = new String(delivery.getBody());

            //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE
            if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_CREATE"))) {
                createNetwork(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_UPDATE"))) {
                updateNetwork(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_DELETE"))) {
                deleteNetwork(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_CREATE"))) {
                createSubnet(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_UPDATE"))) {
                updateSubnet(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_DELETE"))) {
                deleteSubnet(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_CREATE"))) {
                createRouter(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_UPDATE"))) {
                updateRouter(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_DELETE"))) {
                deleteRouter(jsonBody);
            }

            try {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (IOException ex) {
                Logger.error("Could not ack message. Exception: {}", ex);
            }
        }
    });
    networkingThread.start();

    //the load balancer 
    Thread lbThread = new Thread(() -> {
    });

    lbThread.start();

    //the security thread
    Thread securityThread = new Thread(() -> {
        //setup the message receiver
        final Connection connection;
        final Channel channel;
        final QueueingConsumer consumer;

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
        String queueName = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
            queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                    properties.getProperties().getProperty("SECURITY_TOPIC"));
            //                channel.basicQos(Integer.parseUnsignedInt(properties.getProperties().getProperty("PREFETCH_COUNT")));
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException | NullPointerException | NumberFormatException ex) {
            Logger.error("Fatal Error: could not connect to messaging system. Exception: {}", ex);
            return;
        }

        QueueingConsumer.Delivery delivery = null;
        while (true) {
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
                Logger.error("Could not get message from queue. Exception: {}", ex);
                continue;
            }

            String routingKey = delivery.getEnvelope().getRoutingKey();
            String jsonBody = new String(delivery.getBody());

            //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE
            if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_CREATE"))) {
                createSecurityGroup(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_UPDATE"))) {
                updateSecurityGroup(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_DELETE"))) {
                deleteSecurityGroup(jsonBody);
            } else if (routingKey
                    .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_CREATE"))) {
                createSecurityGroupRule(jsonBody);
            } else if (routingKey
                    .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_UPDATE"))) {
                updateSecurityGroupRule(jsonBody);
            } else if (routingKey
                    .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_DELETE"))) {
                deleteSecurityGroupRule(jsonBody);
            }

            try {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (IOException ex) {
                Logger.error("Could not ack message. Exception: {}", ex);
            }
        }
    });
    securityThread.start();
}

From source file:com.gemini.provision.network.main.GeminiNetworkProvisionMainIT.java

@BeforeClass
public static void setUpClass() {
    //load the properties singleton, will be used throughout the tests.
    properties = Guice.createInjector(new GeminiPropertiesModule()).getInstance(GeminiProperties.class);

    //create the mapper in the main class
    //inject the mapper as it will be used in all the threads
    Injector mapperInjector = Guice.createInjector(new GeminiMapperModule());
    mapper = mapperInjector.getInstance(GeminiMapper.class);

    //create the sender
    ConnectionFactory sendMsgFactory = new ConnectionFactory();
    sendMsgFactory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
    try {/*w w w.j ava 2s. c  om*/
        sendMsgConnection = sendMsgFactory.newConnection();
        sendMsgChannel = sendMsgConnection.createChannel();
        sendMsgChannel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
    } catch (IOException ex) {
        Logger.error("Fatal Error: Sender unable to connect to messaging system. Exception: {}", ex);
        fail("Unable to connect to messaging system");
    }

    //create the network receiver
    ConnectionFactory recvNetMsgFactory = new ConnectionFactory();
    recvNetMsgFactory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
    String netQueueName = null;
    try {
        recvNetMsgConnection = recvNetMsgFactory.newConnection();
        recvNetMsgChannel = recvNetMsgConnection.createChannel();
        recvNetMsgChannel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
        netQueueName = recvNetMsgChannel.queueDeclare().getQueue();
        recvNetMsgChannel.queueBind(netQueueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                properties.getProperties().getProperty("NETWORK_TOPIC"));
        recvNetMsgconsumer = new QueueingConsumer(recvNetMsgChannel);
        recvNetMsgChannel.basicConsume(netQueueName, true, recvNetMsgconsumer);
    } catch (IOException | NullPointerException | NumberFormatException ex) {
        Logger.error("Fatal Error: Network receiver could not connect to messaging system. Exception: {}", ex);
        fail("Fatal Error: Receiver could not connect to messaging system.");
    }

    //create the network receiver
    ConnectionFactory recvSecMsgFactory = new ConnectionFactory();
    recvSecMsgFactory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
    String secQueueName = null;
    try {
        recvSecMsgConnection = recvSecMsgFactory.newConnection();
        recvSecMsgChannel = recvSecMsgConnection.createChannel();
        recvSecMsgChannel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
        secQueueName = recvSecMsgChannel.queueDeclare().getQueue();
        recvSecMsgChannel.queueBind(secQueueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                properties.getProperties().getProperty("SECURITY_TOPIC"));
        recvSecMsgconsumer = new QueueingConsumer(recvSecMsgChannel);
        recvSecMsgChannel.basicConsume(secQueueName, true, recvNetMsgconsumer);
    } catch (IOException | NullPointerException | NumberFormatException ex) {
        Logger.error("Fatal Error: Security receiver could not connect to messaging system. Exception: {}", ex);
        fail("Fatal Error: Receiver could not connect to messaging system.");
    }
}

From source file:com.github.cc007.lightsaver.message.rabbitmq.RMQMessageSender.java

public RMQMessageSender(String serverAddress) {
    try {/*from w  w w  . java2 s . c o m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(serverAddress);
        this.con = factory.newConnection();
        this.ch = con.createChannel();
        this.ch.queueDeclare(RMQMessageReceiver.QUEUE_NAME, false, false, false, null);
        this.send = true;
        this.exit = false;
    } catch (IOException ex) {
        Logger.getLogger(RMQMessageSender.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.github.dann.wspusher.pubsub.publisher.impl.RabbitMQPublisherImpl.java

License:Apache License

public void publish(String exchange, String message) {
    Connection connection = null;
    Channel channel = null;//from w  w w  .j a  v a2  s  .c  o m
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(WsConfig.getMQServerHost());
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(exchange, EXCHANGE_TYPE);
        channel.basicPublish(exchange, "", null, message.getBytes(WsConstants.ENCODING_UTF8));

    } catch (Exception e) {
        logger.error("Publishing message faile", e);
        throw new WsRuntimeException("Publishig message failed", e);
    } finally {
        RabbitMQResourceUtils.closeQuietly(channel);
        RabbitMQResourceUtils.closeQuietly(connection);
    }

}

From source file:com.github.hexsmith.rabbitmq.consumer.MessageConsumer.java

License:Open Source License

public boolean consume(String queueName) {
    //RabbitMQ//from w w  w  . j  av a 2 s.co m
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.1");
    Connection connection = null;
    Channel channel = null;
    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
        //queue??queue
        //?queueDeclare???queue
        channel.queueDeclare(queueName, false, false, false, null);

        //?DefaultConsumerhandleDelivery???getByte()???String
        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");
                logger.info("Received '" + message + "'");
            }
        };
        //??
        channel.basicConsume(queueName, true, consumer);

        //???rabbitMQ

    } catch (IOException | TimeoutException e) {
        //?false
        logger.error("send message failed!", e);
        return false;
    }

    return true;
}

From source file:com.github.hexsmith.rabbitmq.consumer.MultiMessageConsumer.java

License:Open Source License

public boolean consume(String queueName, String consumerName) {
    //RabbitMQ/*w  ww . jav  a2 s.c  o  m*/
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.1");
    Connection connection = null;
    Channel channel = null;
    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
        //queue??queue
        //?queueDeclare???queue
        channel.queueDeclare(queueName, false, false, false, null);

        //?DefaultConsumerhandleDelivery???getByte()???String
        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");
                logger.info("[{}]" + "Received '" + message + "'", consumerName);
            }
        };
        //??
        channel.basicConsume(queueName, true, consumer);

        //???rabbitMQ

    } catch (IOException | TimeoutException e) {
        //?false
        logger.error("send message failed!", e);
        return false;
    }

    return true;
}

From source file:com.github.hexsmith.rabbitmq.producer.MessageProducer.java

License:Open Source License

public boolean sendMessage(String message) {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.7");
    Connection connection = null;
    Channel channel = null;/*  ww  w. j  a va 2 s . co m*/
    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        logger.info("send message = {}", message);
        channel.close();
        connection.close();
    } catch (IOException | TimeoutException e) {
        logger.error("send message failed!,exception message is {}", e);
        return false;
    }
    return true;
}