List of usage examples for com.rabbitmq.client Connection createChannel
Channel createChannel() throws IOException;
From source file:org.hobbit.core.rabbit.RabbitRpcClient.java
License:Open Source License
/** * Initializes the client by declaring a request queue using the given * connection and queue name as well as a second queue and a consumer for * retrieving responses./*from w w w . j ava 2s .c o m*/ * * @param connection * the RabbitMQ connection that is used for creating queues * @param requestQueueName * the name of the queue * @throws IOException * if a communication problem during the creation of the * channel, the queue or the internal consumer occurs */ protected void init(Connection connection, String requestQueueName) throws IOException { Channel tempChannel = connection.createChannel(); tempChannel.queueDeclare(requestQueueName, false, false, true, null); requestQueue = new RabbitQueue(tempChannel, requestQueueName); tempChannel = connection.createChannel(); responseQueue = new RabbitQueue(tempChannel, tempChannel.queueDeclare().getQueue()); responseQueue.channel.basicQos(1); RabbitRpcClientConsumer consumer = new RabbitRpcClientConsumer(responseQueue.channel, this); responseQueue.channel.basicConsume(responseQueue.name, true, consumer); }
From source file:org.hp.samples.ProcessMessage.java
License:Open Source License
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.setStatus(200);/*w w w .j a v a 2 s .com*/ PrintWriter writer = response.getWriter(); writer.println("Here's your message:"); // Pull out the RABBITMQ_URL environment variable String uri = System.getenv("RABBITMQ_URL"); ConnectionFactory factory = new ConnectionFactory(); try { factory.setUri(uri); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // Create the queue channel.queueDeclare("hello", false, false, false, null); String routingKey = "thekey"; String exchangeName = "exchange"; // Declare an exchange and bind it to the queue channel.exchangeDeclare(exchangeName, "direct", true); channel.queueBind("hello", exchangeName, routingKey); // Grab the message from the HTML form and publish it to the queue String message = request.getParameter("message"); channel.basicPublish(exchangeName, routingKey, null, message.getBytes()); writer.println(" Message sent to queue '" + message + "'"); boolean autoAck = false; // Get the response message GetResponse responseMsg = channel.basicGet("hello", autoAck); if (responseMsg == null) { // No message retrieved. } else { byte[] body = responseMsg.getBody(); // Since getBody() returns a byte array, convert to a string for // the user. String bodyString = new String(body); long deliveryTag = responseMsg.getEnvelope().getDeliveryTag(); writer.println("Message received: " + bodyString); // Acknowledge that we received the message so that the queue // removes the message so that it's not sent to us again. channel.basicAck(deliveryTag, false); } writer.close(); }
From source file:org.hp.samples.RabbitServlet.java
License:Open Source License
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setStatus(200);/*from w ww . j ava 2 s. c o m*/ PrintWriter writer = response.getWriter(); // Create an HTML form for the user to input a message for the queue String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; writer.println(docType + "<html>" + "<body>" + "<p>RabbitMQ for Java</p>" + "<form action='ProcessMessage' method='post'>" + "Message to send: <input type='text' name='message'><br>" + "<input type='submit' value='Send Message'>" + "</form>" + "</body>" + "</html>"); String uri = System.getenv("RABBITMQ_URL"); ConnectionFactory factory = new ConnectionFactory(); try { factory.setUri(uri); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("hello", false, false, false, null); writer.close(); }
From source file:org.mazerunner.core.messaging.Worker.java
License:Apache License
public void doMain(String[] args) throws Exception { CmdLineParser parser = new CmdLineParser(this); // if you have a wider console, you could increase the value; // here 80 is also the default parser.setUsageWidth(80);// w ww . j av a2s . com try { // parse the arguments. parser.parseArgument(args); if (sparkMaster == "" || hadoopHdfs == "") throw new CmdLineException(parser, "Options required: --hadoop.hdfs <url>, --spark.master <url>"); ConfigurationLoader.getInstance().setHadoopHdfsUri(hadoopHdfs); ConfigurationLoader.getInstance().setSparkHost(sparkMaster); ConfigurationLoader.getInstance().setAppName(sparkAppName); ConfigurationLoader.getInstance().setExecutorMemory(sparkExecutorMemory); ConfigurationLoader.getInstance().setDriverHost(driverHost); ConfigurationLoader.getInstance().setRabbitmqNodename(rabbitMqHost); } catch (CmdLineException e) { // if there's a problem in the command line, // you'll get this exception. this will report // an error message. System.err.println(e.getMessage()); System.err.println("java -cp $CLASSPATH [<spark-config-options>] <main-class> [<mazerunner-args>]"); // print the list of available options parser.printUsage(System.err); System.err.println(); // print option sample. This is useful some time System.err.println(" Example: java -cp $CLASSPATH org.mazerunner.core.messaging.Worker" + parser.printExample(ALL)); return; } ConnectionFactory factory = new ConnectionFactory(); factory.setHost(ConfigurationLoader.getInstance().getRabbitmqNodename()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); channel.basicQos(20); // Initialize spark context GraphProcessor.initializeSparkContext(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(TASK_QUEUE_NAME, false, consumer); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); // Deserialize message Gson gson = new Gson(); ProcessorMessage processorMessage = gson.fromJson(message, ProcessorMessage.class); // Run PageRank GraphProcessor.processEdgeList(processorMessage); System.out.println(" [x] Done '" + message + "'"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } }
From source file:org.muzza.rabbit.RabbitConfig.java
public static Channel getChannel(Connection connection) throws IOException { Channel channel = connection.createChannel(); channel.queueDeclare(Constants.QUEUE, false, false, false, null); return channel; }
From source file:org.ninjav.rabbitmq.SendTest.java
@Test public void canSendMessageToQueue() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); for (int i = 0; i < 1000000; i++) { String message = "Hello world " + i; channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); }//from ww w . j a v a 2s . c om channel.close(); connection.close(); }
From source file:org.ninjav.rabbitmq.TestReceive.java
@Test public void canReceiveMessageFromQueue() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); Consumer consumer;/*from w w w . java2s .c om*/ consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { try { String message = new String(body, "UTF-8"); System.out.println("Message Received: " + message); } finally { channel.basicAck(envelope.getDeliveryTag(), false); } } }; boolean autoAck = false; channel.basicConsume(QUEUE_NAME, autoAck, consumer); try { Thread.sleep(100000); } catch (InterruptedException ex) { Logger.getLogger(TestReceive.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.openbaton.common.vnfm_sdk.amqp.AbstractVnfmSpringAmqp.java
License:Apache License
@Override protected void unregister() { try {/*from w w w.java 2s . c o m*/ ((VnfmSpringHelperRabbit) vnfmHelper).sendMessageToQueue(RabbitConfiguration.queueName_vnfmUnregister, vnfmManagerEndpoint); } catch (IllegalStateException e) { log.warn("Got exception while unregistering trying to do it manually"); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rabbitHost); Connection connection = null; try { connection = factory.newConnection(); Channel channel = connection.createChannel(); String message = gson.toJson(vnfmManagerEndpoint); channel.basicPublish("openbaton-exchange", RabbitConfiguration.queueName_vnfmUnregister, MessageProperties.TEXT_PLAIN, message.getBytes("UTF-8")); log.debug("Sent '" + message + "'"); channel.close(); connection.close(); } catch (IOException e1) { e1.printStackTrace(); } } }
From source file:org.opendaylight.federationmessagequeue.impl.RabbitMessageBus.java
License:Open Source License
@Override public boolean createQueue(String queueName, String mqBrokerIp, int mqPortNumber, String mqUser, String mqUserPwd) {//from ww w . j av a 2 s. c o m LOG.info("Creating connection for queue {} on broker {}", queueName, mqBrokerIp); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(mqBrokerIp); factory.setPort(mqPortNumber); factory.setUsername(mqUser); factory.setPassword(mqUserPwd); factory.setAutomaticRecoveryEnabled(true); try { Connection connection = factory.newConnection(); LOG.info("Created connection to broker {}:{} for user {} ", mqBrokerIp, mqPortNumber, mqUser); Channel channel = connection.createChannel(); channel.queueDeclare(queueName, false, false, false, null); LOG.info("Declared queue {} on broker {}", queueName, mqBrokerIp); MessageBusConnectionData mbcd = new MessageBusConnectionData(mqBrokerIp, connection, channel); queueNameToConnectionData.put(queueName, mbcd); return true; } catch (IOException | TimeoutException e) { LOG.warn("Failed creating queue {} on broker {}:{} for user {} because: {}", queueName, mqBrokerIp, mqPortNumber, mqUser, e.getMessage()); return false; } }
From source file:org.openmrs.module.amqpmodule.utils.impl.PublisherServiceImpl.java
License:Open Source License
@Override public boolean PublisherCreateConnection() throws java.io.IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("192.168.43.123"); factory.setPort(5672);// ww w . j a v a 2 s. com factory.setUsername("chs"); factory.setPassword("chs123"); Connection connection = null; try { connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "direct", true); channel.basicPublish(EXCHANGE_NAME, topic, MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes()); System.out.println(" [x] Sent '" + msg + "'"); channel.close(); } catch (TimeoutException e) { System.out.println("Connection Timed out"); e.printStackTrace(); } connection.close(); return true; }