Ejemplo 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();
    }
  }
Ejemplo n.º 2
0
  public void run() {
    System.out.println(" [x] Awaiting RPC requests");

    while (run.get()) {

      QueueingConsumer.Delivery delivery;
      try {
        delivery = consumer.nextDelivery(2000);
      } catch (ShutdownSignalException e2) {
        break;
      } catch (ConsumerCancelledException e2) {
        break;
      } catch (InterruptedException e2) {
        continue;
      }

      BasicProperties props = delivery.getProperties();
      BasicProperties replyProps =
          new BasicProperties.Builder().correlationId(props.getCorrelationId()).build();

      try {
        Object o;
        synchronized (registry) {
          o = Rmivm.deserialise(delivery.getBody(), registry);
        }

        byte[] outBytes = Rmivm.serialize(o);

        synchronized (channel) {
          channel.basicPublish("", props.getReplyTo(), replyProps, outBytes);
          channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }

      } catch (Exception e) {
        try {
          synchronized (channel) {
            channel.basicPublish(
                "", props.getReplyTo(), replyProps, Rmivm.serialize(new Exception("Boom!")));
          }

        } catch (IOException e1) {
          // panic
        }
      }
    }

    System.out.println(" [x] Shutting Down");
  }
Ejemplo n.º 3
0
  public void sendMessage(String... varStrings) {
    String msg = varStrings[0];
    String exchangeName = varStrings[1];
    String qName = varStrings[2];
    String rabbitIp = varStrings[3];

    logger.debug("RabbitMQ Properties Start...");
    logger.debug("Message - " + msg);
    logger.debug("Exchange Name - " + exchangeName);
    logger.debug("QueueName - " + qName);
    logger.debug("IP Address - " + rabbitIp);
    logger.debug("RabbitMQ Properties End...");

    try {
      CachingConnectionFactory factory = new CachingConnectionFactory();
      factory.setAddresses(rabbitIp);
      org.springframework.amqp.rabbit.connection.Connection connection = factory.createConnection();
      Channel channel = connection.createChannel(false);
      channel.basicPublish(exchangeName, qName, null, msg.getBytes());
      channel.close();
      connection.close();
      logger.debug("Message Sent...");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 4
0
  public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;
    try {
      ConnectionFactory factory = new ConnectionFactory();
      factory.setHost("localhost");

      connection = factory.newConnection();
      channel = connection.createChannel();

      channel.exchangeDeclare(EXCHANGE_NAME, "topic");

      String routingKey = getRouting(argv);
      String message = getMessage(argv);

      channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes());
      System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (Exception ignore) {
        }
      }
    }
  }
  public static void main(String[] argv) throws java.io.IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    System.out.println(
        "Type message to send to logs.\n"
            + "Format ${severity}:${message}\n"
            + "    or ${message} (uses default severity 'error')\n"
            + "Type an empty message to exit this process.");
    try {
      while (true) {
        Message message = getMessage();
        if (message == null) {
          break;
        }
        channel.basicPublish(EXCHANGE_NAME, message.severity, null, message.msg.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
      }
    } finally {
      channel.close();
      connection.close();
    }
  }
  /** Test that an AMQP client can connect to and use the broker. */
  @Test(groups = {"Integration", "WIP"})
  public void testClientConnection() throws Exception {
    rabbit = app.createAndManageChild(EntitySpec.create(RabbitBroker.class));
    rabbit.start(ImmutableList.of(testLocation));
    EntityTestUtils.assertAttributeEqualsEventually(rabbit, Startable.SERVICE_UP, true);

    byte[] content = "MessageBody".getBytes(Charsets.UTF_8);
    String queue = "queueName";
    Channel producer = null;
    Channel consumer = null;
    try {
      producer = getAmqpChannel(rabbit);
      consumer = getAmqpChannel(rabbit);

      producer.queueDeclare(queue, true, false, false, ImmutableMap.<String, Object>of());
      producer.queueBind(queue, AmqpExchange.DIRECT, queue);
      producer.basicPublish(AmqpExchange.DIRECT, queue, null, content);

      QueueingConsumer queueConsumer = new QueueingConsumer(consumer);
      consumer.basicConsume(queue, true, queueConsumer);

      QueueingConsumer.Delivery delivery =
          queueConsumer.nextDelivery(60 * 1000l); // one minute timeout
      assertEquals(delivery.getBody(), content);
    } finally {
      closeSafely(producer, 10 * 1000);
      closeSafely(consumer, 10 * 1000);
    }
  }
Ejemplo n.º 7
0
  public static void main(String[] argv) throws IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("student");
    factory.setPassword("cph");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    String queueName = "Kender du hende der Arne";
    channel.queueDeclare(queueName, false, false, false, null);

    channel.queueBind(queueName, EXCHANGE_NAME, "");
    String messageOut =
        "{\"ssn\":1605789787,\"creditScore\":699,\"loanAmount\":10.0,\"loanDuration\":360}";
    BasicProperties.Builder props = new BasicProperties().builder();
    props.replyTo("");
    BasicProperties bp = props.build();
    channel.basicPublish(EXCHANGE_NAME, "", bp, messageOut.getBytes());
    System.out.println(" [x] Sent by JSONtester: '" + messageOut + "'");

    channel.close();
    connection.close();
  }
 public boolean notice() {
   try {
     String searchServices = VrsMqConfig.VRS_MQ_SEARCH_SERVICE;
     for (String service : searchServices.split(",")) {
       String exchange = "";
       String routingKey = VrsMqConfig.VRS_MQ_ROUTINGKEY + "_search_" + service;
       cfconn.setUri(VrsMqConfig.VRS_MQ_HOSTNAME);
       cfconn.setPort(VrsMqConfig.VRS_MQ_PORT);
       cfconn.setUsername(VrsMqConfig.VRS_MQ_USERNAME);
       cfconn.setPassword(VrsMqConfig.VRS_MQ_PASSWORD);
       Connection conn = cfconn.newConnection();
       Channel ch = conn.createChannel();
       if (exchange.equals("")) {
         ch.queueDeclare(routingKey, false, false, false, null);
       }
       String message = "sync";
       logger.info("=========notice=========:" + message);
       ch.basicPublish(exchange, routingKey, null, message.getBytes());
       ch.close();
       conn.close();
     }
     return true;
   } catch (Exception e) {
     System.err.println("Main thread caught exception: " + e);
     e.printStackTrace();
     return false;
   }
 }
Ejemplo n.º 9
0
 // bug 26552
 public void testServerNamedTransientAutoDeleteQueueAndBindingRecovery()
     throws IOException, InterruptedException, TimeoutException {
   String x = "tmp-fanout";
   Channel ch = connection.createChannel();
   ch.exchangeDelete(x);
   ch.exchangeDeclare(x, "fanout");
   String q = ch.queueDeclare("", false, false, true, null).getQueue();
   final AtomicReference<String> nameBefore = new AtomicReference<String>(q);
   final AtomicReference<String> nameAfter = new AtomicReference<String>();
   final CountDownLatch listenerLatch = new CountDownLatch(1);
   ((AutorecoveringConnection) connection)
       .addQueueRecoveryListener(
           new QueueRecoveryListener() {
             @Override
             public void queueRecovered(String oldName, String newName) {
               nameBefore.set(oldName);
               nameAfter.set(newName);
               listenerLatch.countDown();
             }
           });
   ch.queueBind(nameBefore.get(), x, "");
   restartPrimaryAndWaitForRecovery();
   expectChannelRecovery(ch);
   ch.confirmSelect();
   ch.exchangeDeclare(x, "fanout");
   ch.basicPublish(x, "", null, "msg".getBytes());
   waitForConfirms(ch);
   AMQP.Queue.DeclareOk ok = ch.queueDeclarePassive(nameAfter.get());
   assertEquals(1, ok.getMessageCount());
   ch.queueDelete(nameAfter.get());
   ch.exchangeDelete(x);
 }
  @Test
  public void testBasicConnectivity() {
    String sentMsg = "sent";
    String recvdMsg = "received";
    try {
      channel.queueDeclare(basicTestQueue, false, false, false, null);
      sentMsg = "testBasicConnectivity";
      channel.basicPublish("", basicTestQueue, null, sentMsg.getBytes());

      QueueingConsumer consumer = new QueueingConsumer(channel);
      channel.basicConsume(basicTestQueue, true, consumer);
      QueueingConsumer.Delivery delivery = consumer.nextDelivery(1500);
      if (delivery != null) {
        recvdMsg = new String(delivery.getBody());
      }

    } catch (Exception ex) {
      fail("Connectivity error to MQ while running Test" + ex);
    } finally {
      try {
        channel.close();
        connection.close();
      } catch (Exception ex) {
        fail("Connectivity error to MQ while running Test" + ex);
      }
    }
    assertEquals(sentMsg, recvdMsg);
  }
  @Override
  public Future<Message> sendMessageAsync(final Message message) {
    return EXECUTOR_SERVICE.submit(
        () -> {
          String messageInvalid = messageValidator.validate(message);
          if (messageInvalid != null) {
            logger.info("### Couldn't forward Message .. -> {" + messageInvalid + "}");
            return null;
          } else {
            try {
              Channel rabbitMqChannel = USER_CHANNEL.get(message.getToUser());

              Map<String, Object> headers = new HashMap<>();
              headers.put(ARGUMENT_TO_ID, message.getToUser().getId());
              AMQP.BasicProperties basicProperties =
                  new AMQP.BasicProperties.Builder().headers(headers).build();

              rabbitMqChannel.basicPublish(
                  amqpExchange, "", basicProperties, gson.toJson(message).getBytes("UTF-8"));
              return message;
            } catch (Exception ex) {
              logger.info("### Couldn't forward Message .. -> {" + ex.getMessage() + "}");
              return null;
            }
          }
        });
  }
Ejemplo n.º 12
0
  public static void main(String[] argv) throws java.io.IOException, TimeoutException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    /*
     * The durability options let the tasks survive even if RabbitMQ is
     * restarted
     */
    boolean durable = true;
    channel.queueDeclare(TASK_QUEUE_NAME, durable, false, false, null);

    String message = getMessage(argv);

    /*
     * publish 設成 persistent 的用處是為了防止RabbitMQ server gg 時忘記message 的內容
     */
    channel.basicPublish(
        "", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();
  }
  @Test
  public void testStreamingEvent() {
    // Instantiate the resource
    ResourceImpl resourceImpl = new ResourceImpl(restItem);

    try {
      channel.queueDeclare(intTestQueue, false, false, false, null);
    } catch (Exception ex) {
      fail("Connectivity error to MQ while running Test" + ex);
      try {
        channel.close();
        connection.close();
      } catch (Exception otherEx) {
        // We couldn't close a connection that's already closed or
        // hasn't been open...
      }
    }

    // Here we build the queue ResourceImpl is going to connect to and we
    // will later publish to
    try {
      resourceImpl.startStreaming(createListeners());
    } catch (Exception ex) {
      fail("Error while starting streaming service: " + ex);
    }

    // Have a rest to let all the services start up properly
    try {
      Thread.sleep(5000);
      channel.basicPublish("", intTestQueue, null, mqMessage.getBytes());
    } catch (Exception ex) {
      fail("Cannot publish to MQ on test environment" + ex);
    }

    // A little rest to let the publication go through
    try {
      Thread.sleep(2000);
    } catch (Exception ex) {
    }

    // 1st test: did we get a callback on ConnectedEvent (Connected to MQ) ?
    assertTrue(connectedEventCalled);

    // 2nd test: The stream received event was triggered
    assertTrue(streamEventCalled);

    // 3rd test: And the message received was the same as posted on the
    // Queue
    assertEquals(mqMessage, recvdFromMq);

    resourceImpl.mqDisconnectEvent();
    // Have a rest to let all the services shut down up properly
    try {
      Thread.sleep(2000);
      channel.queuePurge(intTestQueue);
    } catch (Exception ex) {
      // Bit of housekeeping
    }
  }
Ejemplo n.º 14
0
 @Override
 public void enmq(String exchange, Channel ch, MQPacket re) throws IOException {
   byte[] data = re.data;
   if (LOG.isDebugEnabled()) {
     LOG.debug("send data to mq, length:" + data.length);
   }
   ch.basicPublish(exchange, "anomoy", MessageProperties.PERSISTENT_BASIC, data);
 }
Ejemplo n.º 15
0
 private void expectExchangeRecovery(Channel ch, String x)
     throws IOException, InterruptedException, TimeoutException {
   ch.confirmSelect();
   String q = ch.queueDeclare().getQueue();
   final String rk = "routing-key";
   ch.queueBind(q, x, rk);
   ch.basicPublish(x, rk, null, "msg".getBytes());
   waitForConfirms(ch);
   ch.exchangeDeclarePassive(x);
 }
Ejemplo n.º 16
0
 @Override
 public void process(JCas jCas) throws AnalysisEngineProcessException {
   try {
     sendChannel.basicPublish("", queue, PERSISTENT_BASIC, serialize(jCas.getCas()));
     //            LOG.debug(" [RabbitWriter] '" + snippetize(jCas.getDocumentText(), 20)
     //                    + "'");
   } catch (IOException e) {
     throw new AnalysisEngineProcessException(e);
   }
 }
Ejemplo n.º 17
0
 private void expectQueueRecovery(Channel ch, String q)
     throws IOException, InterruptedException, TimeoutException {
   ch.confirmSelect();
   ch.queuePurge(q);
   AMQP.Queue.DeclareOk ok1 = declareClientNamedQueue(ch, q);
   assertEquals(0, ok1.getMessageCount());
   ch.basicPublish("", q, null, "msg".getBytes());
   waitForConfirms(ch);
   AMQP.Queue.DeclareOk ok2 = declareClientNamedQueue(ch, q);
   assertEquals(1, ok2.getMessageCount());
 }
  @Override
  protected void pushMessages(Channel ch) throws IOException {
    String message =
        "{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }\n"
            + "{ \"delete\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n"
            + "{ \"create\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }";

    ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes());
  }
  /**
   *
   * <!-- begin-custom-doc -->
   * <!-- end-custom-doc -->
   *
   * @generated The implementation of this method defines the execution behavior of the synchronous
   *     activity. This method is called by the BusinessWorks Engine on a engine thread to perform
   *     the activity essential functions.
   * @param input This is the activity input data. It is an XML Element which adheres to the input
   *     schema of the activity or <code>null</code> if the activity does not require an input. The
   *     activity input data should be processed using the XML processing context obtained from the
   *     method {@link ProcessContext#getXMLProcessingContext()}.
   * @param processContext Context that is associated with a BusinessWorks Process instance. This
   *     context is unique per BusinessWorks Process instance and it is not visible to other
   *     BusinessWorks Process instances. Also this context is valid only within the BusinessWorks
   *     Engine thread on which this method is invoked. Therefore this context must not be saved or
   *     used by a different thread that is created or managed by the activity implementation.
   * @return An XML Element which adheres to the output schema of the activity or may return <code>
   *     null</code> if the activity does not require an output. This is the activity output data
   *     and it should be created using the XML processing context obtained from the method {@link
   *     ProcessContext#getXMLProcessingContext()}.
   * @throws ActivityFault Thrown if the activity execution is unsuccessful or encounters an error.
   */
  @Override
  public N execute(N input, ProcessContext<N> processContext) throws ActivityFault {
    if (getActivityLogger().isDebugEnabled()) {
      activityLogger.debug(
          RuntimeMessageBundle.DEBUG_PLUGIN_ACTIVITY_METHOD_CALLED,
          new Object[] {
            "execute()",
            activityContext.getActivityName(),
            activityContext.getProcessName(),
            activityContext.getDeploymentUnitName(),
            activityContext.getDeploymentUnitVersion()
          });
      String serializedInputNode =
          XMLUtils.serializeNode(input, processContext.getXMLProcessingContext());
      activityLogger.debug(
          RuntimeMessageBundle.DEBUG_PLUGIN_ACTIVITY_INPUT,
          new Object[] {activityContext.getActivityName(), serializedInputNode});
    }
    N result = null;
    try {
      // begin-custom-code
      String queue =
          getInputParameterStringValueByName(
              input, processContext.getXMLProcessingContext(), "queue");
      String message =
          getInputParameterStringValueByName(
              input, processContext.getXMLProcessingContext(), "message");
      channel.basicPublish("", queue, null, message.getBytes());
      // end-custom-code
      // create output data according the output structure
      result = evalOutput(input, processContext.getXMLProcessingContext(), null);
    } catch (Exception e) {
      throw new ActivityFault(
          activityContext,
          new LocalizedMessage(
              RuntimeMessageBundle.ERROR_OCCURED_RETRIEVE_RESULT,
              new Object[] {activityContext.getActivityName()}));
    }

    if (getActivityLogger().isDebugEnabled()) {
      String serializedOutputNode =
          XMLUtils.serializeNode(result, processContext.getXMLProcessingContext());
      activityLogger.debug(
          RuntimeMessageBundle.DEBUG_PLUGIN_ACTIVITY_OUTPUT,
          new Object[] {
            activityContext.getActivityName(),
            serializedOutputNode,
            activityContext.getActivityName()
          });
    }
    return result;
  }
Ejemplo n.º 20
0
  public static void main(String args[]) throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare("QUEUE_NAME", false, false, false, null);
    String message = "Hello World!";
    channel.basicPublish("", "QUEUE_NAME", null, message.getBytes());
    System.out.println("[x] sent'" + message + "'");

    channel.close();
    connection.close();
  }
Ejemplo n.º 21
0
 public void publish(String msg) {
   try {
     mqConnection.connect();
     Channel chan = mqConnection.conn.createChannel();
     try {
       Builder bob = new BasicProperties.Builder();
       chan.basicPublish("amq.fanout", "chat", bob.build(), msg.getBytes("UTF-8"));
     } finally {
       chan.close();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 22
0
  public static void main(String[] args) throws IOException {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("localhost");
    Connection connection = connectionFactory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    String message = "Hello, World!";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());

    System.out.printf("Sent: %s\n", message);

    channel.close();
    connection.close();
  }
Ejemplo n.º 23
0
 public void alert(String key, String json) {
   String routingKey;
   if (key == null) routingKey = getAlertRoutingKey();
   else routingKey = getAlertRoutingKey() + key;
   try {
     byte[] messageBodyBytes = json.getBytes();
     channel.basicPublish(
         getAlertExchangeName(), routingKey, MessageProperties.TEXT_PLAIN, messageBodyBytes);
   } catch (Exception e) {
     e.printStackTrace();
     try {
       connect();
     } catch (Exception ignored) {
     }
   }
 }
 @Override
 protected void runJob(BackupJob job) {
   try {
     conn.beginOrJoin();
     // we need a JPA-managed instance
     BackupJob job2 = dal.createBackupJobDao().findById(job.getId());
     log.info("Sending job to processing queue: " + job2.getId());
     String json = JsonSerializer.serialize(job2);
     mqChannel.basicPublish("", mqName, null, json.getBytes());
   } catch (IOException e) {
     // Should only happen if message queue is down
     log.fatal(e.getMessage() + " - message queue down?");
     throw new RuntimeException(e);
   } finally {
     conn.rollback();
   }
 }
Ejemplo n.º 25
0
  public void serveRequests() {
    while (true) {
      try {

        Delivery delivery = consumer.nextDelivery();
        BasicProperties props = delivery.getProperties();

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        System.out.println("Received API call...replying...");

        channel.basicPublish("", props.getReplyTo(), null, getResponse(delivery).getBytes("UTF-8"));

      } catch (Exception e) {
        System.out.println(e.toString());
      }
    }
  }
Ejemplo n.º 26
0
 @Override
 public boolean sendStringOnChannel(String string, String exchangeName) {
   try {
     Channel channel = subscribedChannels.get(exchangeName);
     if (channel != null) {
       channel.basicPublish(exchangeName, "", null, string.getBytes());
     }
     Log.i(LOGTAG, "send to: " + exchangeName);
     return true;
   } catch (AlreadyClosedException exception) {
     Log.e(LOGTAG, exchangeName + " : " + exception.toString());
     subscribedChannels.remove(exchangeName);
   } catch (IOException e) {
     Log.e(LOGTAG, "sendStringOnChannel: " + e.toString());
   }
   return false;
 }
 /**
  * Helper method to inject x messages containing y index requests
  *
  * @param ch RabbitMQ channel
  * @param nbMessages number of messages to inject (x)
  * @param nbDocs number of docs per message to inject (y)
  * @throws IOException
  */
 protected static void pushMessages(Channel ch, int nbMessages, int nbDocs) throws IOException {
   for (int i = 0; i < nbMessages; i++) {
     StringBuffer message = new StringBuffer();
     for (int j = 0; j < nbDocs; j++) {
       message.append(
           "{ \"index\" : { \"_index\" : \""
               + INDEX
               + "\", \"_type\" : \"typex\", \"_id\" : \""
               + i
               + "_"
               + j
               + "\" } }\n");
       message.append("{ \"typex\" : { \"field\" : \"" + i + "_" + j + "\" } }\n");
     }
     ch.basicPublish("elasticsearch", "elasticsearch", null, message.toString().getBytes());
   }
 }
Ejemplo n.º 28
0
  public static void main(String[] argv) throws Exception {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    String severity = getSeverity(argv);
    String message = getMessage(argv);

    channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes());
    System.out.println(" [x] Sent '" + severity + "':'" + message + "'");

    channel.close();
    connection.close();
  }
Ejemplo n.º 29
0
  public static void sender(String[] args) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    // true 表示将消息持久化
    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

    String message = getMessage(args);

    // 持久化时,同时需要设置这里的messageProperties
    channel.basicPublish(
        "", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();
  }
Ejemplo n.º 30
0
  public static void t3() throws Exception {
    Channel channel = generateChannel();
    channel.exchangeDeclare(TestAmqp.PingExchangerName, "direct", true, false, null);
    channel.queueDeclare("rpc", false, false, false, null);
    // channel.queueBind(TestAmqp.TopicQueueName, TestAmqp.TopicExchangerName,
    // TestAmqp.RouteingName);
    // channel.queueBind(TestAmqp.TopicQueueName, TestAmqp.TopicExchangerName, "*");
    channel.queueBind("rpc", TestAmqp.PingExchangerName, "ping");

    QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
    channel.basicConsume("rpc", false, queueingConsumer);

    while (true) {
      QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
      System.out.println("log: " + new String(delivery.getBody()));
      channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

      System.out.println("reply to :" + delivery.getProperties().getReplyTo());
      channel.basicPublish("", delivery.getProperties().getReplyTo(), null, "asfasdfas".getBytes());
    }
  }