List of usage examples for com.rabbitmq.client Channel basicConsume
String basicConsume(String queue, boolean autoAck, Consumer callback) throws IOException;
From source file:co.edu.uniandes.cloud.simuladorcredito.negocio.Process.java
public void procesar() { ConnectionFactory factory = new ConnectionFactory(); try {//from www . j a v a 2 s .c o m factory.setUri(uri); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume("hello", true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String mensaje = new String(delivery.getBody()); System.out.println(" [x] Received '" + mensaje + "'"); System.out.println("Procesando..." + mensaje + "-" + Calendar.getInstance()); PlanPago pp = dao.leer(new Long(mensaje)); if (pp.getLinea() != null) { //generar cuota List<Cuota> cuotas = aa.generarCuotas(pp.getValor(), pp.getLinea().getTasa(), pp.getPlazo()); pp.setCuotas(cuotas); //calcular nivel de riesgo pp.setNivelRiesgo(calcularNivelRiesgo()); pp.setEstado("Generado"); //guardar cuota dao.actualizar(pp); for (Cuota c : pp.getCuotas()) { c.setIdPlan(pp.getId()); } dao2.insertar(pp.getCuotas()); } System.out.println("Finalizo " + mensaje + "-" + Calendar.getInstance()); } } catch (URISyntaxException ex) { Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyManagementException ex) { Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex); } //listenerContainer.setConnectionFactory(rabbitConnectionFactory); //listenerContainer.setQueueNames(rabbitQueue.getName()); // set the callback for message handling /*listenerContainer.setMessageListener(new MessageListener() { public void onMessage(Message message) { final String mensaje = (String) messageConverter.fromMessage(message); // simply printing out the operation, but expensive computation could happen here System.out.println("Received from RabbitMQ: " + mensaje); } }); // set a simple error handler /*listenerContainer.setErrorHandler(new ErrorHandler() { public void handleError(Throwable t) { t.printStackTrace(); } }); // register a shutdown hook with the JVM Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("Shutting down BigOperationWorker"); listenerContainer.shutdown(); } }); // start up the listener. this will block until JVM is killed. listenerContainer.start(); System.out.println("BigOperationWorker started"); */ }
From source file:Colas.Colas.java
private String reciver(String enviar) { try {/* w ww.j a va 2 s. co m*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost(IP); factory.setPort(5672); factory.setUsername("valencia"); factory.setPassword("admin123"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("SC", false, false, false, null); channel.basicPublish("", "SC", null, enviar.getBytes()); System.out.println(" [x] Sent '" + enviar + "'"); channel.close(); connection.close(); } catch (Exception e) { System.out.println("Error enviando "); e.printStackTrace(); } try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setUsername("guest"); factory.setPassword("admin123"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("CF", false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume("CF", true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); return message; } } catch (Exception e) { System.out.println("Error reciviendo "); e.printStackTrace(); } return "Error"; }
From source file:Colas.Colas.java
@Override public void run() { try {/*ww w. ja v a 2 s . co m*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setUsername("guest"); factory.setPassword("admin123"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("CF", false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume("CF", true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); String[] resp = message.split(";"); String p = resp[0]; if (p.equals("Q1")) { pregunta1(resp[1]); } if (p.equals("Q2")) { pregunta2(resp[1]); } if (p.equals("Q3")) { pregunta3(resp[1]); } if (p.equals("Q4")) { pregunta4(resp[1]); } } } catch (Exception e) { System.out.println("Error reciviendo "); e.printStackTrace(); } }
From source file:com.abiquo.commons.amqp.util.ConsumerUtils.java
License:Open Source License
public static void startConsumerRequiredAck(Channel channel, Consumer consumer, String queue) throws IOException { channel.basicConsume(queue, false, consumer); }
From source file:com.anteam.demo.rabbitmq.RabbitMQConsumer.java
License:Apache License
public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException { // //from www . j a v a 2 s .c o m ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); // Connection connection = factory.newConnection(); // ?? Channel channel = connection.createChannel(); // ? channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println("[*] Waiting for message. To exist 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()); System.out.println("[x] Received '" + message + "'"); } }
From source file:com.anton.dev.tqrb.MessageListener.java
public static void main(String[] args) throws IOException, TimeoutException, ShutdownSignalException, ConsumerCancelledException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, true, false, false, null); System.out.println(" [*] A la espera de mensajes. Para salir pulse: CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { System.out.println("Obteniendo siguiente mensaje."); QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Recibido: '" + message + "'"); doWork(message);//from w ww .ja va 2 s.com System.out.println(" [x] Hecho!!! "); } }
From source file:com.DeadLetterReceiver.java
License:Open Source License
public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOSTNAME);//from ww w .j ava 2s . com Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); //creating reply queue try { channel.queueDeclarePassive(QUEUE_NAME); } catch (java.io.IOException e) { if (!channel.isOpen()) channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); } System.out.println(" [*] Waiting for responses. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); String message = new String(delivery.getBody()); System.out.println(" [x] Response received '" + message + "'"); System.out.println("Correlation id : " + props.getCorrelationId()); } }
From source file:com.digispherecorp.enterprise.rabbitmq.ra.work.PublishSubcribeRabbitMQWork.java
@Override public void run() { try {/*from w w w .ja v a 2 s . c om*/ Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.INFO, "Work Schedule Polling started @ ".concat(uuid)); if (ipsm == null) { try { Class<?> className = Class .forName(((RabbitMQActivationSpec) activationSpec).getDestinationType()); ipsm = (IPublishSubscribeMessage) className.getConstructor().newInstance(); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { Logger.getLogger(BootStrapRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } } final Channel channel; RabbitMQConnectionFactoryFacade instance = RabbitMQConnectionFactoryFacade.getInstance(); if (instance.getConnectionRequestInfo(activationSpec) == null) { instance.setConnectionRequestInfo(activationSpec, new RabbitMQConnectionRequestInfo(((RabbitMQActivationSpec) activationSpec).getUser(), ((RabbitMQActivationSpec) activationSpec).getPassword(), ((RabbitMQActivationSpec) activationSpec).getHost(), ((RabbitMQActivationSpec) activationSpec).getPort(), ((RabbitMQActivationSpec) activationSpec).getVirtualHost())); } try { connection = instance.getConnection(); channel = connection.createChannel(); channel.exchangeDeclare(((RabbitMQActivationSpec) activationSpec).getExchangeName(), ipsm.getSubscribeType(), isExchangeDurabe(ipsm)); final Consumer consumer = new DefaultConsumer(channel) { @Override public void handleConsumeOk(String consumerTag) { super.handleConsumeOk(consumerTag); } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); if (!envelope.isRedeliver()) { try { RabbitMQMessage mQMessage = new RabbitMQMessage(); mQMessage.getMessages().add(body); try { receiveMessages(mQMessage); } catch (ResourceException ex) { Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } } finally { channel.basicAck(envelope.getDeliveryTag(), true); } } } }; channel.basicConsume(((RabbitMQActivationSpec) activationSpec).getQueueName(), false, consumer); } catch (IOException ex) { Logger.getLogger(RabbitMQResourceAdapter.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } } catch (Exception ex) { Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } }
From source file:com.digispherecorp.enterprise.rabbitmq.ra.work.QueueRabbitMQWork.java
@Override public void run() { try {//www .j a va2s .c o m Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.INFO, "Work Schedule Polling started @ ".concat(uuid)); final Channel channel; RabbitMQConnectionFactoryFacade instance = RabbitMQConnectionFactoryFacade.getInstance(); if (instance.getConnectionRequestInfo(activationSpec) == null) { instance.setConnectionRequestInfo(activationSpec, new RabbitMQConnectionRequestInfo(((RabbitMQActivationSpec) activationSpec).getUser(), ((RabbitMQActivationSpec) activationSpec).getPassword(), ((RabbitMQActivationSpec) activationSpec).getHost(), ((RabbitMQActivationSpec) activationSpec).getPort(), ((RabbitMQActivationSpec) activationSpec).getVirtualHost())); } try { connection = instance.getConnection(); channel = connection.createChannel(); channel.queueDeclarePassive(((RabbitMQActivationSpec) activationSpec).getQueueName()); channel.basicQos(0); final Consumer consumer = new DefaultConsumer(channel) { @Override public void handleConsumeOk(String consumerTag) { super.handleConsumeOk(consumerTag); } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); if (!envelope.isRedeliver()) { try { RabbitMQMessage mQMessage = new RabbitMQMessage(); mQMessage.getMessages().add(body); try { receiveMessages(mQMessage); } catch (ResourceException ex) { Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } } finally { channel.basicAck(envelope.getDeliveryTag(), true); } } } }; channel.basicConsume(((RabbitMQActivationSpec) activationSpec).getQueueName(), false, consumer); } catch (IOException ex) { Logger.getLogger(RabbitMQResourceAdapter.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } } catch (Exception ex) { Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } }
From source file:com.es.dashboard.ConnectionBroker.java
@PostConstruct public void init() { bigBaite = new LinkedList<>(); readings = new ArrayList<Reading>(); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("systembus"); // RabbitMQ IP Connection connection = null; try {/*from w w w.j a v a 2s . co m*/ connection = factory.newConnection(); } catch (IOException ex) { logger.error(ex); } catch (TimeoutException ex) { logger.error(ex); } Channel channel = null; try { channel = connection.createChannel(); } catch (IOException ex) { logger.error(ex); } try { channel.exchangeDeclare("sensors", "topic"); // sensors is the name of the exchange } catch (IOException ex) { logger.error(ex); } AMQP.Queue.DeclareOk result = null; try { result = channel.queueDeclare("", false, true, false, null); } catch (IOException ex) { logger.error(ex); } String queuename = result.getQueue(); try { channel.queueBind(queuename, "sensors", "realtime.sensordata"); // Binding key is #, this will consume all messages channel.queueBind(queuename, "sensors", "realtime.alarms"); // Binding key is #, this will consume all messages } catch (IOException ex) { logger.error(ex); } logger.info(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); EventBus eventBus = EventBusFactory.getDefault().eventBus(); Gson gson = new Gson(); Type type = new TypeToken<Map<String, String>>() { }.getType(); Map<String, String> myMap = gson.fromJson(message, type); if (envelope.getRoutingKey().equals("realtime.alarms")) { eventBus.publish("/channel", message); return; } logger.info(envelope.getRoutingKey()); readings.add(new Reading(new Date(Long.parseLong(myMap.get("timestamp"))), myMap.get("data"), myMap.get("name"), myMap.get("room"))); eventBus.publish("/channel", message); } }; try { //RequestContext.getCurrentInstance().execute("function rpt() {$(\".qualquer\").first().trigger(\"click\")}" // + "var timeoutdummy = window.setInterval(rpt,2000);"); channel.basicConsume(queuename, true, consumer); } catch (IOException ex) { ex.printStackTrace(); logger.error(ex); } }