List of usage examples for com.rabbitmq.client Connection createChannel
Channel createChannel() throws IOException;
From source file:com.vmware.bdd.utils.RabbitMQConsumer.java
License:Open Source License
/** * Receive and process each message until the listener indicating. A new * queue will be created when start and will be deleted when stopping * receiving message.//from w ww . ja v a2 s . com * * FIXME Is it a best practice to create one queue for one task? Or we should * create one thread to handle all messages? * * @param listener * message processor callback * @throws IOException */ public void processMessage(MessageListener listener) throws IOException { ConnectionFactory factory = new ConnectionFactory(); if (username != null && !username.equals("")) { factory.setUsername(username); factory.setPassword(password); } factory.setVirtualHost("/"); factory.setHost(host); factory.setPort(port); Connection conn = factory.newConnection(); Channel channel = conn.createChannel(); /** * make exchange and queue non-durable */ channel.exchangeDeclare(exchangeName, "direct", true); if (!getQueue) { channel.queueDeclare(queueName, false, true, true, null); } else { queueName = channel.queueDeclare().getQueue(); } channel.queueBind(queueName, exchangeName, routingKey); boolean noAck = false; QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, noAck, consumer); while (true) { QueueingConsumer.Delivery delivery; try { delivery = consumer.nextDelivery(mqRecvTimeoutMs); } catch (InterruptedException e) { logger.warn("message consumer interrupted", e); continue; } if (delivery == null) { logger.debug("timeout, no message received"); if (stopping && new Date().after(mqExpireTime)) { logger.error("stop receiving messages without normal termination"); break; } continue; } String message = new String(delivery.getBody()); if (graceStopping) { extendExpirationTime(); } logger.info("message received: " + message); try { if (!listener.onMessage(message)) { logger.info("stop receiving messages normally"); break; } } catch (Throwable t) { logger.error("calling message listener failed", t); // discard and continue in non-debug mode AuAssert.unreachable(); } channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } try { channel.queueDelete(queueName); } catch (AlreadyClosedException e) { logger.error("failed to delete queue: " + queueName, e); } try { channel.close(); } catch (AlreadyClosedException e) { logger.error("failed to close channel, queue: " + queueName, e); } try { conn.close(); } catch (AlreadyClosedException e) { logger.error("failed to close connection, queue: " + queueName, e); } }
From source file:com.vmware.vhadoop.adaptor.rabbit.RabbitConnection.java
License:Open Source License
QueueingConsumer getConsumer() { try {//from ww w . ja va 2 s . c o m Connection connection = _connectionFactory.newConnection(); _channel = connection.createChannel(); String exchangeName = _credentials.getExchangeName(); _channel.exchangeDeclare(exchangeName, "direct", true, false, null); /* TODO: Externalize? */ String queueName = _channel.queueDeclare().getQueue(); _channel.queueBind(queueName, exchangeName, _credentials.getRouteKeyCommand()); QueueingConsumer consumer = new QueueingConsumer(_channel); _channel.basicConsume(queueName, true, consumer); return consumer; } catch (Exception e) { throw new RuntimeException("Unable to get message consumer", e); } }
From source file:com.vmware.vhadoop.vhm.rabbit.RabbitConnection.java
License:Open Source License
private Channel getChannel() throws IOException { synchronized (_channelLock) { if (_channel == null || !_channel.isOpen()) { _log.fine("Creating new channel"); _channel = null;//from w w w . ja v a 2 s . c o m Connection connection = getConnection(); _channel = connection.createChannel(); _channel.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { _log.info("Channel shut down"); _log.log(Level.FINE, "{0}", cause.getReason()); synchronized (_channelLock) { _channel = null; _queueName = null; } _started = false; } }); } return _channel; } }
From source file:com.wakkir.rabbitmq.basic.Reciever.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody(), "UTF-8"); System.out.println(" [x] Received '" + message + "'"); }// w ww .j a va 2s.com }
From source file:com.wakkir.rabbitmq.basic.Sender.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "Hello World!"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + "'"); channel.close();/*from w ww . j a v a 2s. c om*/ connection.close(); }
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 {/* w ww . j a v a2 s . co m*/ 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.zigbee.function.util.MessageUtil.java
License:Open Source License
public static Channel openChannel(String queueName) { ConnectionFactory factory = new ConnectionFactory(); Channel channel;//from w ww. ja v a2s .c o m 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 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 www. ja v a 2s .c om*/ conn.close(); }
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/*w w w .j ava 2s . co 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:controllerStuff.ControllerPublisher.java
/** * * @param connection// ww w .j a v a2 s.c o m * @param controllerObject */ public ControllerPublisher(Connection connection, String nodeID) { this.connection = connection; this.nodeID = nodeID; try { controllerChannel = connection.createChannel(); controllerChannel.exchangeDeclare(EXCHANGE_CONTROLLER_REGETRY, "topic"); } catch (IOException ex) { Logger.getLogger(ControllerPublisher.class.getName()).log(Level.SEVERE, null, ex); } }