List of usage examples for com.rabbitmq.client Connection createChannel
Channel createChannel() throws IOException;
From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java
License:Apache License
public static void main(String[] args) throws Exception { // We use a List to keep track of option insertion order. See below. final List<Option> optionList = new ArrayList<Option>(); optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h")); optionList.add(OptionBuilder.withLongOpt("hostname").hasArg() .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b")); optionList.add(OptionBuilder.withLongOpt("port").hasArg() .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n")); optionList.add(OptionBuilder.withLongOpt("username").hasArg() .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]") .create("u")); optionList.add(OptionBuilder.withLongOpt("password").hasArg() .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]") .create("p")); optionList.add(OptionBuilder.withLongOpt("vhost").hasArg() .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]") .create("v")); optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg() .withDescription("name of the AMQP exchange [required - no default]").create("e")); optionList.add(OptionBuilder.withLongOpt("key").hasArg() .withDescription("the routing key to use when sending messages [default: 'default.routing.key']") .create("k")); optionList.add(OptionBuilder.withLongOpt("type").hasArg() .withDescription("the type of exchange to create [default: 'topic']").create("t")); optionList.add(OptionBuilder.withLongOpt("durable") .withDescription("if set, a durable exchange will be declared [default: not set]").create("d")); optionList.add(OptionBuilder.withLongOpt("autodelete") .withDescription("if set, an auto-delete exchange will be declared [default: not set]") .create("a")); optionList.add(OptionBuilder.withLongOpt("single") .withDescription("if set, only a single message will be sent [default: not set]").create("s")); optionList.add(OptionBuilder.withLongOpt("start").hasArg() .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]") .create());//from ww w. ja v a 2 s. co m optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription( "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]") .create()); optionList.add(OptionBuilder.withLongOpt("interval").hasArg() .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]") .create()); optionList.add(OptionBuilder.withLongOpt("delay").hasArg() .withDescription("the delay between sending messages in milliseconds [default: 100]").create()); // An extremely silly hack to maintain the above order in the help formatting. HelpFormatter formatter = new HelpFormatter(); // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order. formatter.setOptionComparator(new Comparator() { @Override public int compare(Object o1, Object o2) { // I know this isn't fast, but who cares! The list is short. return optionList.indexOf(o1) - optionList.indexOf(o2); } }); // Now we can add all the options to an Options instance. This is dumb! Options options = new Options(); for (Option option : optionList) { options.addOption(option); } CommandLine cmd = null; try { cmd = new BasicParser().parse(options, args); } catch (ParseException e) { formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null); System.exit(1); } if (cmd.hasOption("h")) { formatter.printHelp("RabbitMQProducerMain", options); System.exit(2); } ConnectionFactory factory = new ConnectionFactory(); if (cmd.hasOption("b")) { factory.setHost(cmd.getOptionValue("b")); } if (cmd.hasOption("u")) { factory.setUsername(cmd.getOptionValue("u")); } if (cmd.hasOption("p")) { factory.setPassword(cmd.getOptionValue("p")); } if (cmd.hasOption("v")) { factory.setVirtualHost(cmd.getOptionValue("v")); } if (cmd.hasOption("n")) { factory.setPort(Integer.parseInt(cmd.getOptionValue("n"))); } String exchange = cmd.getOptionValue("e"); String routingKey = "default.routing.key"; if (cmd.hasOption("k")) { routingKey = cmd.getOptionValue("k"); } boolean durable = cmd.hasOption("d"); boolean autoDelete = cmd.hasOption("a"); String type = cmd.getOptionValue("t", "topic"); boolean single = cmd.hasOption("single"); int interval = Integer.parseInt(cmd.getOptionValue("interval", "10")); int delay = Integer.parseInt(cmd.getOptionValue("delay", "100")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date()))); Random r = new Random(); Calendar timer = Calendar.getInstance(); timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00"))); String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}"; Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchange, type, durable, autoDelete, null); do { int wp = (10 + r.nextInt(90)) * 100; String gender = r.nextBoolean() ? "male" : "female"; int age = 20 + r.nextInt(70); String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age); channel.basicPublish(exchange, routingKey, null, line.getBytes()); System.out.println("Sent message: " + line); timer.add(Calendar.SECOND, interval); Thread.sleep(delay); } while ((!single && stop.after(timer.getTime()))); connection.close(); }
From source file:io.druid.firehose.rabbitmq.RabbitMQFirehoseFactory.java
License:Apache License
@Override public Firehose connect(StringInputRowParser firehoseParser) throws IOException { final StringInputRowParser stringParser = firehoseParser; ConnectionOptions lyraOptions = new ConnectionOptions(this.connectionFactory); Config lyraConfig = new Config().withRecoveryPolicy(new RetryPolicy().withMaxRetries(config.getMaxRetries()) .withRetryInterval(Duration.seconds(config.getRetryIntervalSeconds())) .withMaxDuration(Duration.seconds(config.getMaxDurationSeconds()))); String queue = config.getQueue(); String exchange = config.getExchange(); String routingKey = config.getRoutingKey(); boolean durable = config.isDurable(); boolean exclusive = config.isExclusive(); boolean autoDelete = config.isAutoDelete(); final Connection connection = Connections.create(lyraOptions, lyraConfig); connection.addShutdownListener(new ShutdownListener() { @Override/*from w ww . j a v a2s . com*/ public void shutdownCompleted(ShutdownSignalException cause) { log.warn(cause, "Connection closed!"); } }); final Channel channel = connection.createChannel(); channel.queueDeclare(queue, durable, exclusive, autoDelete, null); channel.queueBind(queue, exchange, routingKey); channel.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { log.warn(cause, "Channel closed!"); } }); // We create a QueueingConsumer that will not auto-acknowledge messages since that // happens on commit(). final QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queue, false, consumer); return new Firehose() { /** * Storing the latest delivery as a member variable should be safe since this will only be run * by a single thread. */ private Delivery delivery; /** * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to * and including this tag. See commit() for more detail. */ private long lastDeliveryTag; @Override public boolean hasMore() { delivery = null; try { // Wait for the next delivery. This will block until something is available. delivery = consumer.nextDelivery(); if (delivery != null) { lastDeliveryTag = delivery.getEnvelope().getDeliveryTag(); // If delivery is non-null, we report that there is something more to process. return true; } } catch (InterruptedException e) { // A little unclear on how we should handle this. // At any rate, we're in an unknown state now so let's log something and return false. log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen."); } // This means that delivery is null or we caught the exception above so we report that we have // nothing more to process. return false; } @Override public InputRow nextRow() { if (delivery == null) { //Just making sure. log.wtf("I have nothing in delivery. Method hasMore() should have returned false."); return null; } return stringParser.parse(StringUtils.fromUtf8(delivery.getBody())); } @Override public Runnable commit() { // This method will be called from the same thread that calls the other methods of // this Firehose. However, the returned Runnable will be called by a different thread. // // It should be (thread) safe to copy the lastDeliveryTag like we do below and then // acknowledge values up to and including that value. return new Runnable() { // Store (copy) the last delivery tag to "become" thread safe. final long deliveryTag = lastDeliveryTag; @Override public void run() { try { log.info("Acknowledging delivery of messages up to tag: " + deliveryTag); // Acknowledge all messages up to and including the stored delivery tag. channel.basicAck(deliveryTag, true); } catch (IOException e) { log.error(e, "Unable to acknowledge message reception to message queue."); } } }; } @Override public void close() throws IOException { log.info("Closing connection to RabbitMQ"); channel.close(); connection.close(); } }; }
From source file:io.druid.segment.realtime.firehose.RabbitMQFirehoseFactory.java
License:Open Source License
@Override public Firehose connect() throws IOException { String queue = config.getQueue(); String exchange = config.getExchange(); String routingKey = config.getRoutingKey(); boolean durable = config.isDurable(); boolean exclusive = config.isExclusive(); boolean autoDelete = config.isAutoDelete(); final Connection connection = connectionFactory.newConnection(); connection.addShutdownListener(new ShutdownListener() { @Override/* w w w . j a va 2 s . com*/ public void shutdownCompleted(ShutdownSignalException cause) { log.warn(cause, "Connection closed!"); //FUTURE: we could try to re-establish the connection here. Not done in this version though. } }); final Channel channel = connection.createChannel(); channel.queueDeclare(queue, durable, exclusive, autoDelete, null); channel.queueBind(queue, exchange, routingKey); channel.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { log.warn(cause, "Channel closed!"); //FUTURE: we could try to re-establish the connection here. Not done in this version though. } }); // We create a QueueingConsumer that will not auto-acknowledge messages since that // happens on commit(). final QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queue, false, consumer); return new Firehose() { /** * Storing the latest delivery as a member variable should be safe since this will only be run * by a single thread. */ private QueueingConsumer.Delivery delivery; /** * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to * and including this tag. See commit() for more detail. */ private long lastDeliveryTag; @Override public boolean hasMore() { delivery = null; try { // Wait for the next delivery. This will block until something is available. delivery = consumer.nextDelivery(); if (delivery != null) { lastDeliveryTag = delivery.getEnvelope().getDeliveryTag(); // If delivery is non-null, we report that there is something more to process. return true; } } catch (InterruptedException e) { // A little unclear on how we should handle this. // At any rate, we're in an unknown state now so let's log something and return false. log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen."); } // This means that delivery is null or we caught the exception above so we report that we have // nothing more to process. return false; } @Override public InputRow nextRow() { if (delivery == null) { //Just making sure. log.wtf("I have nothing in delivery. Method hasMore() should have returned false."); return null; } return parser.parse(new String(delivery.getBody())); } @Override public Runnable commit() { // This method will be called from the same thread that calls the other methods of // this Firehose. However, the returned Runnable will be called by a different thread. // // It should be (thread) safe to copy the lastDeliveryTag like we do below and then // acknowledge values up to and including that value. return new Runnable() { // Store (copy) the last delivery tag to "become" thread safe. final long deliveryTag = lastDeliveryTag; @Override public void run() { try { log.info("Acknowledging delivery of messages up to tag: " + deliveryTag); // Acknowledge all messages up to and including the stored delivery tag. channel.basicAck(deliveryTag, true); } catch (IOException e) { log.error(e, "Unable to acknowledge message reception to message queue."); } } }; } @Override public void close() throws IOException { log.info("Closing connection to RabbitMQ"); channel.close(); connection.close(); } }; }
From source file:io.snappydata.rabbitmq.RabbitMQPublisher.java
License:Open Source License
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, true, false, false, null); int logCount = 0; int totalNumLogs = 1000000; while (logCount <= totalNumLogs) { AdImpressionLog log = AdImpressionGenerator.nextRandomAdImpression(); channel.basicPublish("", QUEUE_NAME, null, getLogBytes(log)); logCount += 1;/*from w w w .jav a 2 s . c om*/ if (logCount % 100000 == 0) { System.out.println("RabbitMQPublisher published total " + logCount + " messages"); } } channel.close(); connection.close(); }
From source file:it.av.fac.messaging.rabbitmq.RabbitMQChannelPool.java
public static synchronized Channel createChannel(Connection conn, String queueIn, String queueOut, String routingKeyIn, String routingKeyOut) throws IOException { String UID = obtainUniqueId(queueIn, queueOut, routingKeyIn, routingKeyOut); if (!POOL.containsKey(UID) || !POOL.get(UID).isOpen()) { Channel channel = conn.createChannel(); channel.exchangeDeclare(RabbitMQConstants.EXCHANGE, "direct", true); if (queueIn != null) { channel.queueDeclare(queueIn, false, false, true, null); channel.queueBind(queueIn, RabbitMQConstants.EXCHANGE, routingKeyIn); }// ww w . j a v a 2 s . co m if (queueOut != null) { channel.queueDeclare(queueOut, false, false, true, null); channel.queueBind(queueOut, RabbitMQConstants.EXCHANGE, routingKeyOut); } POOL.put(UID, channel); } return POOL.get(UID); }
From source file:it.jugtorino.one.msvc.way.rabbit.geoip.reference.client.RpcClientExample.java
License:Open Source License
private static Channel setupRabbitMQ() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); Connection connection = factory.newConnection(Collections.singletonList(new Address("localhost"))); Channel channel = connection.createChannel(); channel.queueDeclare("geoip_service_v1", false, false, false, null); return channel; }
From source file:it.jugtorino.one.msvc.way.rabbit.geoip.reference.service.Main.java
License:Open Source License
private static Channel setupRabbitMQ() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); Connection connection = factory.newConnection(Arrays.asList(new Address("localhost"))); Channel channel = connection.createChannel(); channel.queueDeclare("geoip_service_v1", false, false, false, null); return channel; }
From source file:it.jugtorino.one.msvc.way.rabbit.reference.webapp.GeoIPResource.java
License:Open Source License
public GeoIPResource() throws Exception { ConnectionFactory factory = new ConnectionFactory(); Connection connection = factory.newConnection(Collections.singletonList(new Address("localhost"))); Channel channel = connection.createChannel(); channel.queueDeclare("geoip_service_v1", false, false, false, null); client = new RpcClient(channel, "geoip_service_v1"); client.startConsuming();/*from ww w.java2 s . c o m*/ }
From source file:it.txt.ens.authorisationService.amqp.AMQPConnectionHelper.java
License:Apache License
/** * Create an AMQP connection and a channel relating to that connection. * //from w ww .j ava 2 s . c o m */ public Connection connection(String user, String password, String vHost, String Host, Integer port) throws IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(user); factory.setPassword(password); factory.setVirtualHost(vHost); factory.setHost(Host); factory.setPort(port); Connection conn = factory.newConnection(); final Channel c = conn.createChannel(); channel = c; return conn; }
From source file:it.txt.ens.authorisationService.util.AccessRequestEvaluator.java
License:Apache License
private Permission createSubscribingPermissionsAndResources(boolean userAlreadyExists, String operativeHost, int httpPort, int operativePort, String operativeVhost, String ensUsername, String ensPwd, String adminUsername, String adminPwd, PermissionService permissionService, String queueName, String exchangeName) throws ENSResponseFactoryException { if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(MessageFormat.format(MESSAGES.getString("evaluationStep9ExplainationS"), ensUsername, namespace, routingKey)); Connection adminConnection = null; ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(adminUsername);/*w w w. j a va 2s . c o m*/ factory.setPassword(adminPwd); factory.setVirtualHost(operativeVhost); factory.setHost(operativeHost); factory.setPort(operativePort); try { adminConnection = factory.newConnection(); Channel channel = adminConnection.createChannel(); //check if the queue exists if (AMQPQueueHelper.exists(channel, queueName)) { FailureResponseDetails failureDetails = new FailureResponseDetails(); String reason = ErrorCodes.INTERNAL_ERROR; failureDetails.setErrorReason(reason); failureDetails.setErrorCode(ErrorCodes.INTERNAL_ERROR); responseType = ensResponseFactory.createFailureResponse(requestType.getRequestID(), requestType.getTimeStamp(), failureDetails); if (LOGGER.isLoggable(Level.INFO)) LOGGER.log(Level.INFO, MessageFormat.format(MESSAGES.getString("evaluationStep9Failure"), ErrorCodes.INTERNAL_ERROR, reason, MessageFormat.format(MESSAGES.getString("alreadyExistingQueue"), queueName, operativeVhost, operativeHost + ":" + operativePort))); return null; } //forcing creating a new Connection because the following exception is thrown even on new Channel // com.rabbitmq.client.AlreadyClosedException: clean connection shutdown; reason: Attempt to use closed channel // at com.rabbitmq.client.impl.AMQChannel.ensureIsOpen(AMQChannel.java:190) // at com.rabbitmq.client.impl.AMQChannel.rpc(AMQChannel.java:223) // at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:209) // at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:118) // at com.rabbitmq.client.impl.ChannelN.queueDeclare(ChannelN.java:766) // at com.rabbitmq.client.impl.ChannelN.queueDeclare(ChannelN.java:61) // at it.txt.ens.authorisationService.amqp.AMQPQueueHelper.creates(AMQPQueueHelper.java:42) // at it.txt.ens.authorisationService.util.AccessRequestEvaluator.createSubscribingPermissionsAndResources(AccessRequestEvaluator.java:893) // at it.txt.ens.authorisationService.util.AccessRequestEvaluator.executeRabbitMQOperations(AccessRequestEvaluator.java:499) // at it.txt.ens.authorisationService.util.AccessRequestEvaluator.evaluate(AccessRequestEvaluator.java:284) // at it.txt.ens.authorisationService.util.AccessRequestEvaluator.run(AccessRequestEvaluator.java:216) // at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) // at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) // at java.util.concurrent.FutureTask.run(Unknown Source) // at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) // at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) // at java.lang.Thread.run(Unknown Source) adminConnection.close(); adminConnection = factory.newConnection(); AMQPQueueHelper.creates(adminConnection.createChannel(), queueName, false, false, true); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(MessageFormat.format(MESSAGES.getString("evaluationStep9OK-1S"), queueName, operativeVhost, operativeHost + ":" + operativePort)); adminConnection.createChannel().queueBind(queueName, exchangeName, routingKey); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine( MessageFormat.format(MESSAGES.getString("evaluationStep9OK-2S"), queueName, exchangeName)); // if (userAlreadyExists) // return mergePermissions(permissionService , operativeVhost, ensUsername, "", "", queueName); // else return new Permission(operativeVhost, ensUsername, "", "", queueName); } catch (Exception e) { FailureResponseDetails failureDetails = new FailureResponseDetails(); String reason = MESSAGES.getString(ErrorCodes.ENS_RESOURCE_RESERVATION_FAILURE); failureDetails.setErrorReason(reason); failureDetails.setErrorCode(ErrorCodes.ENS_RESOURCE_RESERVATION_FAILURE); responseType = ensResponseFactory.createFailureResponse(requestType.getRequestID(), requestType.getTimeStamp(), failureDetails); if (LOGGER.isLoggable(Level.INFO)) LOGGER.log(Level.INFO, MessageFormat.format(MESSAGES.getString("evaluationStep9Failure"), ErrorCodes.ENS_RESOURCE_RESERVATION_FAILURE, reason, e.getMessage()), e); return null; } finally { if (adminConnection != null) try { adminConnection.close(); } catch (IOException e) { } } }