List of usage examples for com.rabbitmq.client Channel basicConsume
String basicConsume(String queue, boolean autoAck, Consumer callback) throws IOException;
From source file:es.devcircus.rabbitmq_examples.rabbitmq_rpc.RPCServer.java
License:Open Source License
/** * * @param argv//from ww w.j a va 2s. c o m */ public static void main(String[] argv) { Connection connection = null; Channel channel = null; try { ConnectionFactory factory = new ConnectionFactory(); // factory.setHost("localhost"); factory.setHost("192.168.0.202"); // factory.setPort(5671); // factory.useSslProtocol(); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_QUEUE_NAME, false, consumer); System.out.println(" [x] Awaiting RPC requests"); while (true) { String response = null; 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"); int n = Integer.parseInt(message); System.out.println(" [.] fib(" + message + ")"); response = "" + fib(n); } catch (Exception e) { System.out.println(" [.] " + e.toString()); response = ""; } finally { channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8")); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (IOException | InterruptedException | ShutdownSignalException | ConsumerCancelledException e) { System.out.println(e.toString()); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }
From source file:es.devcircus.rabbitmq_examples.rabbitmq_topics.ReceiveLogsTopic.java
License:Open Source License
/** * //from w ww . j ava 2 s .c o m * @param argv */ public static void main(String[] argv) { Connection connection = null; Channel channel = null; try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); String queueName = channel.queueDeclare().getQueue(); if (argv.length < 1) { System.err.println("Usage: ReceiveLogsTopic [binding_key]..."); System.exit(1); } for (String bindingKey : argv) { channel.queueBind(queueName, EXCHANGE_NAME, bindingKey); } System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); String routingKey = delivery.getEnvelope().getRoutingKey(); System.out.println(" [x] Received '" + routingKey + "':'" + message + "'"); } } catch (IOException | InterruptedException | ShutdownSignalException | ConsumerCancelledException e) { } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }
From source file:es.devcircus.rabbitmq_examples.rabbitmq_work_queues.Worker.java
License:Open Source License
/** * /*from w w w .j a v a2s . c o m*/ * @param argv * @throws Exception */ 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(TASK_QUEUE_NAME, true, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); channel.basicQos(1); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(TASK_QUEUE_NAME, false, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); doWork(message); System.out.println(" [x] Done"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } }
From source file:eu.betaas.rabbitmq.subscriber.SubscriberService.java
License:Apache License
public void startService() { try {//from ww w.j a va 2 s . co m log.info("#Starting queue #"); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection; log.info("#Starting #"); connection = factory.newConnection(); log.info("#Starting connection#"); Channel channel = connection.createChannel(); channel.exchangeDeclare(ename, mode); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, ename, bussubkey); log.info("#Starting connection on queue #"); consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); log.info("#Running #"); run(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ShutdownSignalException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ConsumerCancelledException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:gash.router.server.MessageServer.java
License:Apache License
public void createQueue() throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException, SQLException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("inbound_queue", false, false, false, null); channel.basicQos(1);//from w ww .j a va 2 s . c o m postgre = new PostgreSQL(url, username, password, dbname, ssl); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume("inbound_queue", false, consumer); // Map<String, byte[]> map = new HashMap<String, byte[]>(); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); String request = props.getType(); System.out.println(request); if (request != null) { if (request.equals("get")) { String key = new String(delivery.getBody()); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); byte[] image = postgre.get(key); channel.basicPublish("", props.getReplyTo(), replyProps, image); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } if (request.equals("put")) { byte[] image = delivery.getBody(); postgre.put(props.getUserId(), image); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); channel.basicPublish("", props.getReplyTo(), replyProps, image); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } if (request.equals("post")) { System.out.println("Message Server"); String key = postgre.post(delivery.getBody()); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); channel.basicPublish("", props.getReplyTo(), replyProps, key.getBytes()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } if (request.equals("delete")) { String key = new String(delivery.getBody()); postgre.delete(key); } } } }
From source file:genqa.ExportRabbitMQVerifier.java
License:Open Source License
public void run() throws IOException, InterruptedException { final Connection connection = m_connFactory.newConnection(); final Channel channel = connection.createChannel(); try {//w w w.ja v a2 s .co m channel.exchangeDeclare(m_exchangeName, "topic", true); String dataQueue = channel.queueDeclare().getQueue(); channel.queueBind(dataQueue, m_exchangeName, "EXPORT_PARTITIONED_TABLE.#"); channel.queueBind(dataQueue, m_exchangeName, "EXPORT_PARTITIONED_TABLE2.#"); channel.queueBind(dataQueue, m_exchangeName, "EXPORT_REPLICATED_TABLE.#"); channel.queueBind(dataQueue, m_exchangeName, "EXPORT_PARTITIONED_TABLE_FOO.#"); channel.queueBind(dataQueue, m_exchangeName, "EXPORT_PARTITIONED_TABLE2_FOO.#"); channel.queueBind(dataQueue, m_exchangeName, "EXPORT_REPLICATED_TABLE_FOO.#"); String doneQueue = channel.queueDeclare().getQueue(); channel.queueBind(doneQueue, m_exchangeName, "EXPORT_DONE_TABLE.#"); channel.queueBind(doneQueue, m_exchangeName, "EXPORT_DONE_TABLE_FOO.#"); // Setup callback for data stream channel.basicConsume(dataQueue, false, createConsumer(channel)); // Setup callback for the done message QueueingConsumer doneConsumer = new QueueingConsumer(channel); channel.basicConsume(doneQueue, true, doneConsumer); // Wait until the done message arrives, then verify count final QueueingConsumer.Delivery doneMsg = doneConsumer.nextDelivery(); final long expectedRows = Long.parseLong(ExportOnServerVerifier.RoughCSVTokenizer .tokenize(new String(doneMsg.getBody(), Charsets.UTF_8))[6]); while (expectedRows > m_verifiedRows) { Thread.sleep(1000); System.err.println("Expected " + expectedRows + " " + m_verifiedRows); } } finally { tearDown(channel); channel.close(); connection.close(); } }
From source file:getbanks2.GetBanks2.java
/** * @param args the command line arguments * @throws java.io.IOException// w ww. j a va 2s . c o m * @throws java.util.concurrent.TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); factory.setUsername("Dreamteam"); factory.setPassword("bastian"); Connection connection = factory.newConnection(); Channel listeningChannel = connection.createChannel(); Channel sendingChannel = connection.createChannel(); listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(listeningChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); String[] arr = message.split(","); String banks = getBanks(arr[0], Integer.parseInt(arr[1]), Double.parseDouble(arr[2]), Integer.parseInt(arr[3])); message += "," + banks; System.out.println(message); sendingChannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null); sendingChannel.basicPublish("", SENDING_QUEUE_NAME, null, message.getBytes()); } }; listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer); }
From source file:getcreditscore.GetCreditScore.java
public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); factory.setUsername("Dreamteam"); factory.setPassword("bastian"); Connection connection = factory.newConnection(); Channel sendingChannel = connection.createChannel(); Channel listeningChannel = connection.createChannel(); listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null); Consumer consumer = new DefaultConsumer(listeningChannel) { @Override/* ww w. ja v a 2 s . c om*/ public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); String[] arr = message.split(","); sendingChannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null); String message = arr[0] + "," + creditScore(arr[0]) + "," + arr[1] + "," + arr[2]; sendingChannel.basicPublish("", SENDING_QUEUE_NAME, null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); } }; listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer); }
From source file:in.cs654.chariot.ashva.AshvaServer.java
License:Open Source License
public static void main(String[] args) { Connection connection = null; Channel channel; try {/*ww w. j av a2 s . c om*/ final ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST_IP_ADDR); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); final QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_QUEUE_NAME, false, consumer); LOGGER.info("Ashva Server started. Waiting for requests..."); AshvaHelper.joinOrStartChariotPool(); AshvaHelper.startHeartbeat(); while (true) { final QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicResponse response = new BasicResponse(); BasicRequest request = new BasicRequest(); final BasicProperties props = delivery.getProperties(); final BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); try { final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>( BasicRequest.class); decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder); request = avroReader.read(request, decoder); response = AshvaProcessor.process(request); } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in handling request: " + e.getMessage()); response = ResponseFactory.getErrorResponse(request); } finally { baos.reset(); final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>( BasicResponse.class); encoder = EncoderFactory.get().binaryEncoder(baos, encoder); avroWriter.write(response, encoder); encoder.flush(); LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus()); channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in RPC server: " + e.getMessage()); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }
From source file:in.cs654.chariot.prashti.PrashtiServer.java
License:Open Source License
public static void main(String[] args) { Connection connection = null; Channel channel; try {/*from ww w.j av a 2 s .c om*/ final ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST_IP_ADDR); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); final QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_QUEUE_NAME, false, consumer); LOGGER.info("Prashti Server started. Waiting for requests..."); final List<Prashti> prashtiList = D2Client.getOnlinePrashtiServers(); final String ipAddr = CommonUtils.getIPAddress(); prashtiList.add(new Prashti(ipAddr)); LOGGER.info("Notifying D2 to set Prashti Server IP Address"); D2Client.setPrashtiServers(prashtiList); while (true) { final QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicResponse response = new BasicResponse(); BasicRequest request = new BasicRequest(); final BasicProperties props = delivery.getProperties(); final BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); try { final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>( BasicRequest.class); decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder); request = avroReader.read(request, decoder); response = RequestProcessor.process(request); } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in handling request: " + e.getMessage()); response = ResponseFactory.getErrorResponse(request); } finally { baos.reset(); final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>( BasicResponse.class); encoder = EncoderFactory.get().binaryEncoder(baos, encoder); avroWriter.write(response, encoder); encoder.flush(); LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus()); channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in RPC server: " + e.getMessage()); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }