Exemplo n.º 1
1
  /** @param args [0] RabbitmqHost */
  public static void main(String[] args) {
    System.out.println(Constants.HEADER);
    String RabbitmqHost = "localhost";
    if (args.length > 0) RabbitmqHost = args[0];

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(RabbitmqHost);

    try {
      Connection connection = factory.newConnection();
      System.out.println("Connected: " + RabbitmqHost);
      Channel channel = connection.createChannel();
      channel.exchangeDeclare(Constants.exchange, "direct", false);
      Stats stats = new Stats();
      JSONWriter rabbitmqJson = new JSONWriter();
      int msgCount = 0;
      for (; ; ) {
        stats.Update();
        String statMsg = rabbitmqJson.write(stats);
        System.out.println(stats.toString());
        channel.basicPublish(Constants.exchange, Constants.routingKey, null, statMsg.getBytes());
        ++msgCount;
        if (System.in.available() > 0) break;
        Thread.sleep(1000);
      }
      channel.close();
      System.out.println("Done: " + msgCount + " messages sent");
      connection.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void handleDelivery(
      String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
      throws java.io.IOException {

    String reply = null;
    try {
      String message = new String(body);
      Integer idToFind = (Integer) jsonReader.read(message);
      System.out.println("Searching for: " + idToFind);
      Book book = bookstore.GetBook(idToFind);

      reply = book != null ? jsonWriter.write(book) : "ERROR: BOOK not found";
      System.out.println("JSON response: " + reply);
    } catch (Exception e) {
      reply = "ERROR: internal server error";
      System.err.println(e);
    } finally {
      BasicProperties replyProperties =
          new BasicProperties.Builder().correlationId(properties.getCorrelationId()).build();
      // you have to send the reply on the client
      // the client is blocked until this publish.
      // In rpc mode it's important send always a reply.
      getChannel().basicPublish("", properties.getReplyTo(), replyProperties, reply.getBytes());
      // The message must be removed form the queue.
      // Anyway if the sever can't remove the message the client is safe
      // with the correlation id attribute.
      getChannel().basicAck(envelope.getDeliveryTag(), false);
    }
  }