Advertisement
Kyrexar

[IAP] Consumidor1

Oct 16th, 2019 (edited)
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | None | 0 0
  1. package consumidor;
  2.  
  3. import java.io.IOException;
  4. import java.util.concurrent.TimeoutException;
  5.  
  6. import com.rabbitmq.client.AMQP;
  7. import com.rabbitmq.client.Channel;
  8. import com.rabbitmq.client.Connection;
  9. import com.rabbitmq.client.ConnectionFactory;
  10. import com.rabbitmq.client.Consumer;
  11. import com.rabbitmq.client.DefaultConsumer;
  12. import com.rabbitmq.client.Envelope;
  13.  
  14. /**
  15.  * @author adsosmar
  16.  * @version pract1
  17.  */
  18. public class Consumidor {
  19.     private final static String NOMBRE_COLA = "saludo";
  20.  
  21.     public static void main(String [] args) throws IOException, TimeoutException {
  22.         // Conectarse con RabbitMQ
  23.         ConnectionFactory factory = new ConnectionFactory();
  24.         factory.setHost("localhost");
  25.         Connection connection = factory.newConnection();
  26.  
  27.         // Crear un canal de comunicación
  28.         Channel channel = connection.createChannel();
  29.  
  30.         // Declaramos la cola para producir mensajes
  31.         channel.queueDeclare(NOMBRE_COLA, false, false, false, null);
  32.  
  33.         // Crear un manejador de mensajes
  34.         Consumer consumer = new DefaultConsumer(channel) {
  35.             @Override
  36.             public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
  37.                     byte[] body) throws IOException {
  38.                 String message = new String(body, "UTF-8");
  39.                 System.out.println("Recibido: '" + message + "'");
  40.                
  41.                 try {
  42.                     Thread.sleep(2000);
  43.                 } catch (InterruptedException e) {
  44.                     // TODO Auto-generated catch block
  45.                     e.printStackTrace();
  46.                 }
  47.                
  48.                 // Cerrar canal y conexión, si no se quiere recibir más
  49.                 if (message.equals("cerrar") && connection.isOpen()) {
  50.                     connection.close();
  51.                 }
  52.             }
  53.         };
  54.         channel.basicConsume(NOMBRE_COLA, true, consumer);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement