Kyrexar

[IAP] Consumidor3

Oct 16th, 2019 (edited)
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1. package consumidor3;
  2.  
  3. import java.io.IOException;
  4. import java.util.Scanner;
  5. import java.util.concurrent.TimeoutException;
  6.  
  7. import com.rabbitmq.client.AMQP;
  8. import com.rabbitmq.client.BuiltinExchangeType;
  9. import com.rabbitmq.client.Channel;
  10. import com.rabbitmq.client.Connection;
  11. import com.rabbitmq.client.ConnectionFactory;
  12. import com.rabbitmq.client.Consumer;
  13. import com.rabbitmq.client.DefaultConsumer;
  14. import com.rabbitmq.client.Envelope;
  15.  
  16. public class Consumidor3 {
  17.     private final static String NOMBRE_EXCHANGE = "fallas";
  18.  
  19.     public static void main(String[] args) throws IOException, TimeoutException {
  20.         // Conectarse con RabbitMQ
  21.         ConnectionFactory factory = new ConnectionFactory();
  22.         factory.setHost("localhost");
  23.         Connection connection = factory.newConnection();
  24.  
  25.         // Crear un canal de comunicación
  26.         Channel channel = connection.createChannel();
  27.  
  28.         // Declaramos un Exchange de tipo Topic
  29.         channel.exchangeDeclare(NOMBRE_EXCHANGE, BuiltinExchangeType.TOPIC);
  30.  
  31.         // Solicitar la creación de una cola y asociarle los temas de los mensajes a
  32.         // recibir
  33.         String COLA_CONSUMER = channel.queueDeclare().getQueue();
  34.  
  35.         Scanner ent = new Scanner(System.in);
  36.        
  37.         System.out.println("Introduce lejos o cerca:");
  38.  
  39.         String texto = ent.nextLine();
  40.        
  41.         ent.close();
  42.  
  43.         channel.queueBind(COLA_CONSUMER, NOMBRE_EXCHANGE, texto);
  44.  
  45.         // Crear un manejador de mensajes
  46.         Consumer consumer = new DefaultConsumer(channel) {
  47.             @Override
  48.             public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
  49.                     byte[] body) throws IOException {
  50.                 String message = new String(body, "UTF-8");
  51.                 System.out.println("Recibido: '" + message + "'");
  52.             }
  53.         };
  54.         channel.basicConsume(COLA_CONSUMER, true, consumer);
  55.     }
  56. }
Add Comment
Please, Sign In to add comment