Example usage for com.rabbitmq.client ConnectionFactory ConnectionFactory

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

Introduction

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

Prototype

ConnectionFactory

Source Link

Usage

From source file:com.workingflow.akka.commons.rabbit.ConnectionFactoryProducer.java

License:Apache License

@Produces
@Singleton/*from   w  ww  .  j a v  a  2 s. com*/
public ConnectionFactory getConnectionFactory() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    return factory;
}

From source file:com.wss.log.LogController.java

public LogController() throws IOException, TimeoutException {
    factory = new ConnectionFactory();
    factory.setUsername(Constant.RABBITMQ_USERNAME);
    factory.setPassword(Constant.RABBITMQ_PASSWORD);
    factory.setVirtualHost(Constant.RABBITMQ_VIRTUAL_HOST);
    factory.setRequestedChannelMax(Constant.NUM_BROKER);
    factory.setHost(Constant.RABBITMQ_HOST);
    connection = factory.newConnection();
    channel = connection.createChannel();
    channel.queueDeclare(Constant.QUEUE_NAME, Constant.QUEUE_DURABLE, false, false, null);
}

From source file:com.wss.qvh.log.ConsumerThread.java

public void consumer() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(Constant.RABBITMQ_USERNAME);
    factory.setPassword(Constant.RABBITMQ_PASSWORD);
    factory.setVirtualHost(Constant.RABBITMQ_VIRTUAL_HOST);
    factory.setRequestedChannelMax(Constant.NUM_PRODUCER);
    factory.setHost(Constant.RABBITMQ_HOST);

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

    channel.queueDeclare(Constant.QUEUE_NAME, Constant.QUEUE_DURABLE, false, false, null);
    channel.basicQos(Constant.QUEUE_PREFETCH);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    boolean autoAck = false;
    channel.basicConsume(Constant.QUEUE_NAME, autoAck, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery;
        try {//from   ww w.  j  a  v a 2  s  . c  om
            delivery = consumer.nextDelivery();
        } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
            logger.warn(ex.getMessage(), ex);
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex1) {
                logger.warn(ex1.getMessage(), ex1);
            }
            continue;
        }

        String message;
        try {
            message = getMessenge(delivery);
        } catch (InterruptedException ex) {
            logger.warn(ex.getMessage(), ex);
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex1) {
                logger.warn(ex1.getMessage(), ex1);
            }
            continue;
        }
        if (message == null || message.isEmpty()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                logger.warn(ex.getMessage(), ex);
            }
        } else {
            LogObject lo = new LogObject();
            try {
                lo.parseJson(message);
                store(lo);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (Exception ex) {
                logger.debug(message, ex);
            }
        }
    }
}

From source file:com.zero_x_baadf00d.play.module.rabbitmq.RabbitMQModuleImpl.java

License:Open Source License

/**
 * Build an instance.//from  w ww  . j a  v  a  2s .c om
 *
 * @param lifecycle     The current application lifecyle
 * @param configuration The current application configuration
 * @since 16.05.19
 */
@Inject
public RabbitMQModuleImpl(final ApplicationLifecycle lifecycle, final Config configuration) {
    this.configuration = configuration;
    try {
        final String uri = configuration.getString(RabbitMQModuleImpl.RABBITMQ_CONN_URI);
        if (uri == null || uri.isEmpty()) {
            throw new RuntimeException("URI is empty");
        }
        final ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(uri);
        connectionFactory
                .setRequestedHeartbeat(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_HEARTBEAT));
        connectionFactory
                .setNetworkRecoveryInterval(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_RECOVERY));
        connectionFactory.setConnectionTimeout(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_TIMEOUT));
        connectionFactory.setAutomaticRecoveryEnabled(
                configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_AUTO_RECOVERY));
        if (uri.toLowerCase(Locale.ENGLISH).startsWith("amqps://")) {
            connectionFactory.useSslProtocol();
        }

        final ExecutorService es = Executors
                .newFixedThreadPool(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_EXECUTOR));
        this.rabbitConnection = connectionFactory.newConnection(es);
        RabbitMQModuleImpl.LOGGER.info("RabbitMQ connected at {}",
                String.format("amqp%s://%s:%d/%s", connectionFactory.isSSL() ? "s" : "",
                        connectionFactory.getHost(), connectionFactory.getPort(),
                        connectionFactory.getVirtualHost()));
    } catch (Exception ex) {
        this.rabbitConnection = null;
        if (!this.configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_BYPASS_ERROR)) {
            RabbitMQModuleImpl.LOGGER.error("Can't initialize RabbitMQ module", ex);
            throw new RuntimeException(ex);
        } else {
            RabbitMQModuleImpl.LOGGER.warn("Can't initialize RabbitMQ module: {}", ex.getMessage());
        }
    }

    lifecycle.addStopHook(() -> {
        RabbitMQModuleImpl.LOGGER.info("Shutting down RabbitMQ");
        if (this.rabbitConnection != null) {
            this.rabbitConnection.close();
        }
        return CompletableFuture.completedFuture(null);
    });
}

From source file:com.zigbee.function.util.MessageUtil.java

License:Open Source License

public static Channel openChannel(String queueName) {
    ConnectionFactory factory = new ConnectionFactory();

    Channel channel;/*from   w w w.  j av  a 2  s . com*/
    try {
        factory.setHost("45.63.124.106");
        Connection connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(queueName, false, false, false, null);
        return channel;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TimeoutException e) {
        e.printStackTrace();
    }
    return null;

}

From source file:com.zuehlke.carrera.javapilot.show.ConfirmDontLoseMessages.java

License:Mozilla Public License

public static void main2(String[] args) throws IOException, InterruptedException {
    if (args.length > 0) {
        msgCount = Integer.parseInt(args[0]);
    }//w w  w .j a  va2  s. co  m

    connectionFactory = new ConnectionFactory();

    // Consume msgCount messages.
    (new Thread(new Consumer())).start();
    // Publish msgCount messages and wait for confirms.
    (new Thread(new Publisher())).start();
}

From source file:com.zuehlke.carrera.javapilot.show.ConfirmDontLoseMessages.java

License:Mozilla Public License

public static void main1(String[] args) throws IOException, InterruptedException, TimeoutException {

    connectionFactory = new ConnectionFactory();
    String POWER_QUEUE = "/app/pilots/power";
    String json = new JacksonSerializer().serialize(new PowerControl(200, "team", "access", 0L));
    Connection conn = connectionFactory.newConnection();
    Channel ch = conn.createChannel();
    //ch.queueDeclare(POWER_QUEUE, true, false, false, null);
    AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().expiration("0").build();
    ch.basicPublish("", POWER_QUEUE, props, json.getBytes());

    String SENSOR_QUEUE = "/topic/pilots/starterkit/sensor";
    SensorEvent sensorEvent = SensorEvent.createEmptyCarSensor().withRaceTrackId("simulator");
    json = new JacksonSerializer().serialize(sensorEvent);

    //ch.queueDeclare(SENSOR_QUEUE, true, false, false, null);
    ch.basicPublish("", SENSOR_QUEUE, props, json.getBytes());

    ch.close();/*from  ww w .  java2 s  .c  o  m*/
    conn.close();
}

From source file:communication.queueManager.ACQueueManagement.java

License:Mozilla Public License

@Override
protected void createConnectionAndChannel() {
    Log.logger.info("Creating a connection and channel");
    QueueParameters hostQueueParameters = ACNetwork.ACMessageQueueParameters;
    factory = new ConnectionFactory();
    factory.setHost(queueParameters.queueHostIP);//Add the RabbiMQ host here
    factory.setPort(Integer.parseInt(hostQueueParameters.port));
    factory.setUsername(hostQueueParameters.username);
    factory.setPassword(hostQueueParameters.password);
    factory.setVirtualHost(hostQueueParameters.virtualHost);
    Log.logger.info(hostQueueParameters.toString());
    // factory.setRequestedHeartbeat(0);
    try {//  w ww.  j  av  a  2  s. c o m
        conn = factory.newConnection();

        channel = conn.createChannel();
        channel.basicQos(prefetchCount);
        channel.exchangeDeclare(hostQueueParameters.exchange, "fanout");
        channel.queueDeclare(hostQueueParameters.queueName, false, false, true, null);
        // TODO: Test exchange code here
        channel.queueBind(hostQueueParameters.queueName, hostQueueParameters.exchange,
                hostQueueParameters.routingKey);
        this.setupQueueListener = true;
        Log.logger.info("Finished creating connection and channel");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:controllers.TargetController.java

License:Open Source License

/**
 * This method pushes a message onto a RabbitMQ queue for given target
 * using global settings from project configuration file.
 *
 * @param target The field URL of the target
 * @return//from   w w w . ja va 2s  . c  o m
 */
public static Result archive(Long id) {

    Target target = Target.findById(id);
    Logger.debug("archiveTarget() " + target);
    if (target != null) {
        if (!target.isInScopeAllOrInheritedWithoutLicense()) {
            return ok(infomessage.render("On-demand archiving is only supported for NPLD targets."));
        }

        // Send the message:
        try {
            String queueHost = Play.application().configuration().getString(Const.QUEUE_HOST);
            String queuePort = Play.application().configuration().getString(Const.QUEUE_PORT);
            String queueName = Play.application().configuration().getString(Const.QUEUE_NAME);
            String routingKey = Play.application().configuration().getString(Const.ROUTING_KEY);
            String exchangeName = Play.application().configuration().getString(Const.EXCHANGE_NAME);

            Logger.debug("archiveTarget() queue host: " + queueHost);
            Logger.debug("archiveTarget() queue port: " + queuePort);
            Logger.debug("archiveTarget() queue name: " + queueName);
            Logger.debug("archiveTarget() routing key: " + routingKey);
            Logger.debug("archiveTarget() exchange name: " + exchangeName);

            JsonNode jsonData = Json.toJson(target);
            String message = jsonData.toString();
            Logger.debug("Crawl Now message: " + message);

            ConnectionFactory factory = new ConnectionFactory();
            if (queueHost != null) {
                factory.setHost(queueHost);
            }
            if (queuePort != null) {
                factory.setPort(Integer.parseInt(queuePort));
            }
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            channel.exchangeDeclare(exchangeName, "direct", true);
            channel.queueDeclare(queueName, true, false, false, null);
            channel.queueBind(queueName, exchangeName, routingKey);

            BasicProperties.Builder propsBuilder = new BasicProperties.Builder();
            propsBuilder.deliveryMode(2);
            channel.basicPublish(exchangeName, routingKey, propsBuilder.build(), message.getBytes());

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

        } catch (IOException e) {
            String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator.";
            User currentUser = User.findByEmail(request().username());
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String msgFullTrace = sw.toString();
            Logger.error(msgFullTrace);
            if (currentUser.hasRole("sys_admin")) {
                msg = msgFullTrace;
            }
            return ok(infomessage.render(msg));
        } catch (Exception e) {
            String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator.";
            User currentUser = User.findByEmail(request().username());
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String msgFullTrace = sw.toString();
            Logger.error(msgFullTrace);
            if (currentUser.hasRole("sys_admin")) {
                msg = msgFullTrace;
            }
            return ok(infomessage.render(msg));
        }
    } else {
        Logger.debug("There was a problem sending the message. Target field for archiving is empty");
        return ok(infomessage
                .render("There was a problem sending the message. Target field for archiving is empty"));
    }
    return ok(ukwalicenceresult.render());
}

From source file:coyote.dx.reader.RabbitReader.java

License:Open Source License

/**
 * @see coyote.dx.reader.AbstractFrameReader#open(coyote.dx.context.TransformContext)
 *//*from   w  w  w .j  av  a2s.co  m*/
@Override
public void open(TransformContext context) {
    super.open(context);

    ConnectionFactory factory = new ConnectionFactory();

    try {
        factory.setUri(getBrokerURI());
        if (useSSL()) {
            factory.useSslProtocol();
        }

        String username = getUsername();
        if (StringUtil.isNotBlank(username)) {
            factory.setUsername(username);
            factory.setPassword(getPassword());
        }

        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.basicQos(prefetchCount);
        channel.queueDeclare(getQueueName(), DURABLE, PUBLIC, KEEP, NO_ARGUMENTS);
    } catch (KeyManagementException | NoSuchAlgorithmException | URISyntaxException | IOException
            | TimeoutException | ShutdownSignalException | ConsumerCancelledException e) {
        Log.error(e.getClass().getSimpleName() + ":" + e.getMessage() + "\n" + ExceptionUtil.stackTrace(e));
        getContext().setError("Could not open " + getClass().getSimpleName() + ": " + e.getMessage());
    }

}