List of usage examples for com.rabbitmq.client ConnectionFactory newConnection
public Connection newConnection() throws IOException, TimeoutException
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.//w ww .jav a 2 s . c om * * 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.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 + "'"); }//from w w w . ja va 2 s .c o m }
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 w w. j a v a2s . com 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 w w. jav a2s. 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.zigbee.function.util.MessageUtil.java
License:Open Source License
public static Channel openChannel(String queueName) { ConnectionFactory factory = new ConnectionFactory(); Channel channel;//from www . jav a2 s . c om 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: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 ww w . ja v a 2 s .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 .jav a 2s.c o 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()); } }
From source file:coyote.dx.writer.RabbitWriter.java
License:Open Source License
/** * @see coyote.dx.writer.AbstractFrameFileWriter#open(coyote.dx.context.TransformContext) *///w w w .java 2s . c o m @Override public void open(TransformContext context) { super.open(context); String format = getFormat(); if (StringUtil.isNotBlank(format)) { if (format.equalsIgnoreCase(JSON) || format.equalsIgnoreCase(XML)) { String encoding = getEncoding(); try { "Testing".getBytes(encoding); } catch (final java.io.UnsupportedEncodingException e) { Log.error("Unsupported string encoding of '" + encoding + "'"); getContext().setError("Unsupported string encoding of '" + encoding + "'"); } } } else { Log.error("Unsupported message format of '" + format + "' JSON, XML, and Binary are the currently supported options"); getContext().setError("Unsupported message format of '" + format + "'"); } 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.queueDeclare(getQueueName(), true, false, false, null); } 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()); } }
From source file:coyote.mq.AbstractMessagingTest.java
License:Open Source License
public void sendMessage(String queueName, DataFrame message) { if (StringUtil.isNotBlank(queueName) && message != null) { byte[] data = message.getBytes(); try {//from w w w . j a v a 2 s . c om ConnectionFactory factory = new ConnectionFactory(); factory.setUri(broker.getBrokerUri()); factory.useSslProtocol(); // username:password should be in the URI for our tests try (Connection connection = factory.newConnection()) { Channel channel = connection.createChannel(); channel.queueDeclare(queueName, false, false, false, null); channel.basicPublish("", queueName, null, data); Log.debug("Sent " + data.length + " bytes to '" + queueName + "'"); } } catch (Exception e) { Log.error("Could not send message: " + e.getClass().getSimpleName() + "-" + e.getMessage()); } } }
From source file:cs.rsa.ts14dist.appserver.RabbitMQDaemon.java
License:Apache License
@Override public void run() { Connection connection = null; Channel channel = null;/*from w w w.j a v a2 s . c om*/ try { ConnectionFactory factory = new ConnectionFactory(); logger.info("Starting RabbitMQDaemon, MQ IP = " + hostname); factory.setHost(hostname); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(rpcQueueName, false, false, false, null); channel.basicQos(1); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(rpcQueueName, false, consumer); while (true) { String response = null; // Block and fetch next msg from queue QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()) .build(); try { String message = new String(delivery.getBody(), "UTF-8"); logger.trace("Received msg: " + message); // Convert the message to a JSON request object JSONObject request = (JSONObject) JSONValue.parse(message); // Delegate to the server request handler for handling the // request and computing an answer JSONObject reply = serverRequestHandler.handleRequest(request); // Convert the answer back into a string for replying to // client response = reply.toJSONString(); } catch (Exception e) { logger.error(" Exception in MQDAemon run()/while true] " + e.toString()); response = "wrong"; } finally { logger.trace("Returning answer: " + response); channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8")); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); logger.trace("Answer acknowledged."); } } } catch (Exception e) { logger.error("Exception in daemon's outer loop: nested exception" + e.getMessage()); e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }