Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package consumidor2;
- import java.io.IOException;
- import java.util.Scanner;
- import java.util.concurrent.TimeoutException;
- import org.dom4j.Document;
- import org.dom4j.DocumentHelper;
- import org.dom4j.Element;
- import org.json.JSONException;
- import org.json.JSONObject;
- import com.rabbitmq.client.AMQP;
- import com.rabbitmq.client.BuiltinExchangeType;
- import com.rabbitmq.client.Channel;
- import com.rabbitmq.client.Connection;
- import com.rabbitmq.client.ConnectionFactory;
- import com.rabbitmq.client.Consumer;
- import com.rabbitmq.client.DefaultConsumer;
- import com.rabbitmq.client.Envelope;
- public class Consumidor2 {
- private final static String NOMBRE_EXCHANGE = "deportes";
- public static void main(String[] args) throws IOException, TimeoutException {
- // Conectarse con RabbitMQ
- ConnectionFactory factory = new ConnectionFactory();
- factory.setHost("localhost");
- Connection connection = factory.newConnection();
- // Crear un canal de comunicación
- Channel channel = connection.createChannel();
- // Declaramos un Exchange de tipo Topic
- channel.exchangeDeclare(NOMBRE_EXCHANGE, BuiltinExchangeType.TOPIC);
- // Solicitar la creación de una cola y asociarle los temas de los mensajes a
- // recibir
- String COLA_CONSUMER = channel.queueDeclare().getQueue();
- Scanner ent = new Scanner(System.in);
- System.out.println("Introduce deportes separados por comas:");
- String texto = ent.nextLine();
- String deportes[] = texto.split(",");
- ent.close();
- for (int i = 0; i < deportes.length; i++) {
- channel.queueBind(COLA_CONSUMER, NOMBRE_EXCHANGE, deportes[i].trim());
- }
- // Crear un manejador de mensajes
- 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");
- System.out.println("Recibido: '" + message + "'");
- try {
- JSONObject json;
- json = new JSONObject(message);
- Document document = DocumentHelper.createDocument();
- Element root = document.addElement("Mensajes");
- Element mensaje = root.addElement("Mensaje");
- mensaje.addElement("Fecha").addText(json.get("fecha").toString());
- mensaje.addElement("Texto").addText(json.get("texto").toString());
- System.out.println(document.asXML());
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- };
- channel.basicConsume(COLA_CONSUMER, true, consumer);
- }
- }
Add Comment
Please, Sign In to add comment