Example usage for com.rabbitmq.client ConnectionFactory setPort

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

Introduction

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

Prototype

public void setPort(int port) 

Source Link

Document

Set the target port.

Usage

From source file:org.springframework.amqp.rabbit.core.RabbitAdminIntegrationTests.java

License:Apache License

/**
 * Verify that a queue exists using the native Rabbit API to bypass all the connection and
 * channel caching and callbacks in Spring AMQP.
 *
 * @param queue The queue to verify/*from  w  w w .j  ava  2  s  .c om*/
 * @return True if the queue exists
 */
private boolean queueExists(final Queue queue) throws Exception {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("localhost");
    connectionFactory.setPort(BrokerTestUtils.getPort());
    Connection connection = connectionFactory.newConnection();
    Channel channel = connection.createChannel();
    try {
        DeclareOk result = channel.queueDeclarePassive(queue.getName());
        return result != null;
    } catch (IOException e) {
        return e.getCause().getMessage().contains("RESOURCE_LOCKED");
    } finally {
        connection.close();
    }
}

From source file:org.springframework.amqp.rabbit.MulticastMain.java

License:Mozilla Public License

public static void main(String[] args) {
    Options options = getOptions();/*  w  ww . jav  a 2s .  c om*/
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('?')) {
            usage(options);
            System.exit(0);
        }

        String hostName = strArg(cmd, 'h', "localhost");
        int portNumber = intArg(cmd, 'p', AMQP.PROTOCOL.PORT);
        String exchangeType = strArg(cmd, 't', "direct");
        String exchangeName = strArg(cmd, 'e', exchangeType);
        int samplingInterval = intArg(cmd, 'i', 1);
        int rateLimit = intArg(cmd, 'r', 0);
        int producerCount = intArg(cmd, 'x', 1);
        int messageCount = intArg(cmd, 'N', 0);
        int consumerCount = intArg(cmd, 'y', 1);
        int connectionCount = cmd.hasOption('c') ? 1 : consumerCount;
        int producerTxSize = intArg(cmd, 'm', 0);
        int consumerTxSize = intArg(cmd, 'n', 0);
        boolean autoAck = cmd.hasOption('a');
        int prefetchCount = intArg(cmd, 'q', 0);
        int minMsgSize = intArg(cmd, 's', 0);
        int timeLimit = intArg(cmd, 'z', 0);
        List<String> flags = lstArg(cmd, 'f');
        int frameMax = intArg(cmd, 'M', 0);
        int heartbeat = intArg(cmd, 'b', 0);

        // setup
        String id = UUID.randomUUID().toString();
        Stats stats = new Stats(1000L * samplingInterval);
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostName);
        factory.setPort(portNumber);
        factory.setRequestedFrameMax(frameMax);
        factory.setRequestedHeartbeat(heartbeat);

        Connection[] consumerConnections = new Connection[connectionCount];
        for (int i = 0; i < connectionCount; i++) {
            Connection conn = factory.newConnection();
            consumerConnections[i] = conn;
        }
        Thread[] consumerThreads = new Thread[consumerCount];
        for (int i = 0; i < consumerCount; i++) {
            System.out.println("starting consumer #" + i);
            Connection conn = consumerConnections[i % connectionCount];
            Channel channel = conn.createChannel();
            if (consumerTxSize > 0)
                channel.txSelect();
            channel.exchangeDeclare(exchangeName, exchangeType);
            String queueName = channel.queueDeclare("", flags.contains("persistent"), true, false, null)
                    .getQueue();
            QueueingConsumer consumer = new QueueingConsumer(channel);
            if (prefetchCount > 0)
                channel.basicQos(prefetchCount);
            channel.basicConsume(queueName, autoAck, consumer);
            channel.queueBind(queueName, exchangeName, id);
            Thread t = new Thread(new Consumer(consumer, id, consumerTxSize, autoAck, stats, timeLimit));
            consumerThreads[i] = t;
            t.start();
        }
        Thread[] producerThreads = new Thread[producerCount];
        Connection[] producerConnections = new Connection[producerCount];
        for (int i = 0; i < producerCount; i++) {
            System.out.println("starting producer #" + i);
            Connection conn = factory.newConnection();
            producerConnections[i] = conn;
            Channel channel = conn.createChannel();
            if (producerTxSize > 0)
                channel.txSelect();
            channel.exchangeDeclare(exchangeName, exchangeType);
            final Producer p = new Producer(channel, exchangeName, id, flags, producerTxSize,
                    1000L * samplingInterval, rateLimit, minMsgSize, timeLimit, messageCount);
            channel.addReturnListener(p);
            Thread t = new Thread(p);
            producerThreads[i] = t;
            t.start();
        }

        for (int i = 0; i < producerCount; i++) {
            producerThreads[i].join();
            producerConnections[i].close();
        }

        for (int i = 0; i < consumerCount; i++) {
            consumerThreads[i].join();
        }
        for (int i = 0; i < connectionCount; i++) {
            consumerConnections[i].close();
        }

    } catch (ParseException exp) {
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        usage(options);
    } catch (Exception e) {
        System.err.println("Main thread caught exception: " + e);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:org.springframework.cloud.vault.config.rabbitmq.VaultConfigRabbitMqTests.java

License:Apache License

@Test
public void shouldConnectUsingRabbitMQClient() throws Exception {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(RABBITMQ_HOST);/*w w  w . ja  va2  s.com*/
    factory.setPort(RABBITMQ_PORT);
    factory.setUsername(username);
    factory.setPassword(password);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.close();
    connection.close();
}

From source file:org.teksme.server.common.messaging.AMQPBrokerManager.java

License:Apache License

protected Connection connect(MessageMiddleware msgMiddlewareConfig) throws IOException {

    logger.info("Connecting to AMQP broker...");

    ConnectionFactory connFactory = new ConnectionFactory();
    connFactory.setUsername(msgMiddlewareConfig.getUsername());
    connFactory.setPassword(msgMiddlewareConfig.getPasswd());
    connFactory.setVirtualHost(msgMiddlewareConfig.getVirtualHost());
    connFactory.setHost(msgMiddlewareConfig.getHost());
    connFactory.setRequestedHeartbeat(0);
    connFactory.setPort(
            msgMiddlewareConfig.getPort() == null ? AMQP.PROTOCOL.PORT : msgMiddlewareConfig.getPort());

    toString(connFactory);//from   w  w w. j a v  a2 s.co m

    try {
        conn = connFactory.newConnection();
    } catch (Exception e) {
        e.printStackTrace();
    }
    conn.addShutdownListener(this);

    logger.info("RabbitMQ AMQP broker connected!");

    return conn;
}

From source file:org.thingsboard.rule.engine.rabbitmq.TbRabbitMqNode.java

License:Apache License

@Override
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
    this.config = TbNodeUtils.convert(configuration, TbRabbitMqNodeConfiguration.class);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(this.config.getHost());
    factory.setPort(this.config.getPort());
    factory.setVirtualHost(this.config.getVirtualHost());
    factory.setUsername(this.config.getUsername());
    factory.setPassword(this.config.getPassword());
    factory.setAutomaticRecoveryEnabled(this.config.isAutomaticRecoveryEnabled());
    factory.setConnectionTimeout(this.config.getConnectionTimeout());
    factory.setHandshakeTimeout(this.config.getHandshakeTimeout());
    this.config.getClientProperties().forEach((k, v) -> factory.getClientProperties().put(k, v));
    try {/*from  w  ww.j a v  a2 s  .  c o m*/
        this.connection = factory.newConnection();
        this.channel = this.connection.createChannel();
    } catch (Exception e) {
        throw new TbNodeException(e);
    }
}

From source file:org.trianacode.TrianaCloud.Broker.BrokerServletContextListener.java

License:Open Source License

public void contextInitialized(ServletContextEvent event) {
    ServletContext sc = event.getServletContext();

    String host = sc.getInitParameter("rabbitmq.host");
    int port = Integer.parseInt(sc.getInitParameter("rabbitmq.port"));
    String user = sc.getInitParameter("rabbitmq.user");
    String pass = sc.getInitParameter("rabbitmq.pass");
    String rpc_queue_name = sc.getInitParameter("rabbitmq.rpc_queue_name");
    String vHost = sc.getInitParameter("rabbitmq.vhost");

    ConcurrentHashMap<String, Task> taskMap = new ConcurrentHashMap<String, Task>();
    ConcurrentHashMap<String, Task> resultMap = new ConcurrentHashMap<String, Task>();

    receiver = new Receiver(host, port, user, pass, vHost);
    rpcServer = new RPCServer(host, port, user, pass, vHost, rpc_queue_name);

    String replyQueue = receiver.init();
    try {//from   ww w.  jav a 2 s. c o  m
        rpcServer.init();
    } catch (ServletException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

    receiverThread = new Thread(receiver);
    receiverThread.start();

    rpcServerThread = new Thread(rpcServer);
    rpcServerThread.start();

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);
    factory.setPort(port);
    factory.setUsername(user);
    factory.setPassword(pass);

    sc.setAttribute("RabbitMQConnectionFactory", factory);
    sc.setAttribute("taskmap", taskMap);
    sc.setAttribute("replyQueue", replyQueue);
    sc.setAttribute("resultMap", resultMap);
    sc.setAttribute("rpc_queue_name", rpc_queue_name);
}

From source file:org.trianacode.TrianaCloud.Broker.Receiver.java

License:Open Source License

public String init() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);/*from   www .j a  va 2s  .  c o m*/
    factory.setPort(port);
    factory.setUsername(user);
    factory.setPassword(password);
    factory.setVirtualHost(vHost);
    factory.setConnectionTimeout(60);

    try {
        connection = factory.newConnection();
        channel = connection.createChannel();

        consumer = new QueueingConsumer(channel);
        receiveQueueName = channel.queueDeclare("", false, false, true, null).getQueue();
        channel.basicConsume(receiveQueueName, true, consumer);
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        return null;
    }

    return receiveQueueName;
}

From source file:org.trianacode.TrianaCloud.Broker.RPCServer.java

License:Open Source License

public void init() throws ServletException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);/*w w w.  ja  v  a 2  s. c o m*/
    factory.setPort(port);
    factory.setUsername(user);
    factory.setPassword(password);
    factory.setVirtualHost(vHost);
    factory.setConnectionTimeout(60);
    try {
        keepRunning = true;
        td = new TaskDAO();

        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(rpc_queue_name, false, false, false, null);

        channel.basicQos(1);

        consumer = new QueueingConsumer(channel);
        channel.basicConsume(rpc_queue_name, false, consumer);
        logger.info("[x] Awaiting RPC requests");
    } catch (Exception e) {
        ServletException se = new ServletException(e);
        logger.fatal("Something Happened!", se);
        throw se;
    }
}

From source file:org.trpr.mule.transport.rabbitmq.RabbitConnector.java

License:Apache License

/**
 * Abstract method implementation. Creates the AMQP connection
 * @see org.mule.transport.AbstractConnector#doConnect()
 *//*from  w  ww .j av  a2s  . c om*/
protected void doConnect() throws Exception {
    if (connection == null) {
        int totalNumberOfNodes = rabbitMQConfigurations.size();
        int tries = 0;
        while (tries <= totalNumberOfNodes) {
            int index = (lastUsedConnectionIndex + 1) % totalNumberOfNodes;
            RabbitMQConfiguration rabbitMQConfiguration = null;
            try {
                ConnectionFactory factory = new ConnectionFactory();
                rabbitMQConfiguration = rabbitMQConfigurations.get(index);
                factory.setUsername(rabbitMQConfiguration.getUserName());
                factory.setPassword(rabbitMQConfiguration.getPassword());
                factory.setVirtualHost(rabbitMQConfiguration.getVirtualHost());
                factory.setRequestedHeartbeat(rabbitMQConfiguration.getRequestHeartBeat());
                factory.setHost(rabbitMQConfiguration.getHostName());
                factory.setPort(rabbitMQConfiguration.getPortNumber());
                connection = factory.newConnection();
                lastUsedConnectionIndex = index;
                logger.info("Connection successfully created to configuration = " + rabbitMQConfiguration);
                return;
            } catch (Exception e) {
                logger.info("Failed to connect to Rabbit MQ Node. Configuration is " + rabbitMQConfiguration
                        + ". Will try other configurations");
            }
            tries++;
        }
        logger.error("Failed to connect to all configured Rabbit MQ nodes");
        throw new Exception("Failed to connect to all configured Rabbit MQ nodes");
    }
}

From source file:org.trpr.platform.integration.impl.messaging.RabbitConnectionHolder.java

License:Apache License

/**
 * Helper method to create RabbitMQ {@link Connection} and {@link Channel} for the specified {@link RabbitMQRpcConfiguration}
 * @param configuration the RabbitMQRpcConfiguration or one of its sub-types to create connection objects for
 * @throws MessagingException in case of errors during connection & channel creation
 *//*from   w  w  w.  ja  v  a  2s.  com*/
private void createConnection(RabbitMQRpcConfiguration configuration) throws MessagingException {

    synchronized (this) { // all code blocks that mutate the connection and channel objects held by this class are synchronized

        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(configuration.getUserName());
        factory.setPassword(configuration.getPassword());
        factory.setVirtualHost(configuration.getVirtualHost());
        factory.setRequestedHeartbeat(configuration.getRequestHeartBeat());
        factory.setHost(configuration.getHostName());
        factory.setPort(configuration.getPortNumber());

        try {
            // create the connection
            this.conn = factory.newConnection();
            // add a shutdown listener to the newly created connection
            this.conn.addShutdownListener(this);
            // create the channel
            this.channel = this.conn.createChannel();
            this.channel.exchangeDeclare(configuration.getExchangeName(), configuration.getExchangeType(),
                    configuration.isDurable());

        } catch (Exception e) {
            LOGGER.error("Error initializing RabbitMQ connection for : " + configuration.toString(), e);
            throw new MessagingException(
                    "Error initializing RabbitMQ connection for : " + configuration.toString()); //not passing the root cause as it is logged here
        }
    }

}