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();
    }
  }
Exemplo n.º 2
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();
  }
  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();
    }
  }
  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    try {
      channel.exchangeDeclare(EXCHANGE_NAME, "direct");
      String queueName = channel.queueDeclare().getQueue();

      String severity = "warning";
      channel.queueBind(queueName, EXCHANGE_NAME, severity);

      System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

      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(
                  " [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
            }
          };
      channel.basicConsume(queueName, true, consumer);
      while (true) {}
    } finally {
      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;
   }
 }
Exemplo n.º 6
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) {
        }
      }
    }
  }
  private void runIt() throws IOException {
    Channel channel = _connection.createChannel();

    String queueName = "test queue";
    channel.queueDeclare(queueName, true, false, false, null);

    String exchangeName = "test completion";
    channel.exchangeDeclare(exchangeName, "fanout", false, false, null);

    String completionQueue = channel.queueDeclare().getQueue();
    channel.queueBind(completionQueue, exchangeName, "");

    LatencyExperimentConsumer callback = new LatencyExperimentConsumer(channel, queueName);
    callback._autoAck = this._autoAck;

    channel.basicConsume(queueName, _autoAck, callback);
    channel.basicConsume(completionQueue, true, "completion", callback);
    callback.report(_writeStats);

    System.out.println("Deleting test queue.");
    channel.queueDelete(queueName);

    System.out.println("Deleting completion queue.");
    channel.queueDelete(completionQueue);

    System.out.println("Closing the channel.");
    channel.close();

    System.out.println("Closing the connection.");
    _connection.close();

    System.out.println("Leaving ConsumerMain.run().");
  }
 /**
  *
  * <!-- begin-custom-doc -->
  * <!-- end-custom-doc -->
  *
  * @generated This method is called when an activity is destroyed. It is called by the
  *     BusinessWorks Engine and the method must be implemented to release or cleanup any resources
  *     held by this activity.
  */
 @Override
 public void destroy() {
   if (this.getActivityLogger().isDebugEnabled()) {
     activityLogger.debug(
         RuntimeMessageBundle.DEBUG_PLUGIN_ACTIVITY_METHOD_CALLED,
         new Object[] {
           "destroy()",
           activityContext.getActivityName(),
           activityContext.getProcessName(),
           activityContext.getDeploymentUnitName(),
           activityContext.getDeploymentUnitVersion()
         });
   }
   // begin-custom-code
   // add your own business code here
   try {
     channel.close();
     connection.close();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (TimeoutException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   // end-custom-code
   super.destroy();
 }
  @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);
  }
Exemplo n.º 10
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();
  }
  @Test
  public void testDisconnectViaExceeded() {
    // Make the test run a little faster
    SystemProperties.setProperty("ss.echo_sender_interval", "1");
    SystemProperties.setProperty("ss.echo_max_missed_echos", "2");
    // Instatiate 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 the echo count expire
    try {
      Thread.sleep(30000);
    } catch (Exception ex) {
      fail("Interrupted sleep cycle" + ex);
    }
    // 1st test: did the echo count get increased by the batch echo sends?
    assertTrue(disconnectedEventCalled);

    try {
      channel.queuePurge(resourceId);
      channel.close();
      connection.close();
    } catch (Exception otherEx) {
      // We couldn't close a connection that's already closed or hasn't
      // been open...
    }
  }
  @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
    }
  }
Exemplo n.º 13
0
 public void closeConnection() {
   if (connection != null) {
     try {
       connection.close();
     } catch (Exception ignore) {
     }
   }
 }
  @Test
  public void testConnectedDisconnectedEvents() {
    // 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) {
        fail(
            "Error while closing MQ channle, may have been closed alreadyConnectivity error to MQ while running Test"
                + ex);
      }
    }

    // 1st test: We should, at this stage not received a ConnectedEvent yet
    assertFalse(connectedEventCalled);

    // 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: " + ex);
    }

    // Have a rest to let all the services start up properly
    try {
      Thread.sleep(5000);
    } catch (Exception ex) {
      // Cleaning a queue gave us problems? yikes!
    }

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

    // 3rd test: We should, at this stage not received a DisconnectedEvent
    // yet
    assertFalse(disconnectedEventCalled);

    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
    }

    // 4th test: did we get a callback on DisconnectedEvent (Disconnected
    // from MQ) ?
    assertTrue(disconnectedEventCalled);
  }
Exemplo n.º 15
0
  public void stop() throws IOException {
    if (channel != null && channel.isOpen()) {
      channel.close();
    }

    if (connection != null && connection.isOpen()) {
      connection.close();
    }
  }
Exemplo n.º 16
0
 public void close() {
   try {
     channel.close();
     conn.close();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (TimeoutException e) {
     e.printStackTrace();
   }
 }
 @Override
 public void shutdown() {
   super.shutdown();
   try {
     mqChannel.close();
     mqConnection.close();
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Exemplo n.º 18
0
 public void disconnect() {
   status = AMBStatus.DISCONNECTED;
   try {
     channel.close();
     connection.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
   channel = null;
 }
Exemplo n.º 19
0
 @Override
 protected void closeImpl() throws IOException {
   // ! We are going to assume that closing an already closed
   //  connection is considered success.
   if (connection != null && connection.isOpen()) {
     try {
       connection.close(factory.getConnectionTimeout());
     } catch (AlreadyClosedException ignored) {
     }
   }
 }
Exemplo n.º 20
0
  public void StopConsumer() {

    try {
      channel.basicCancel(consumerTag);
      channel.close();
      connection.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 @PreDestroy
 public void stop() {
   try {
     messageAcker.stop();
     producerChannel.close();
     consumerChannel.close();
     clientConnection.close();
   } catch (IOException | TimeoutException e) {
     logger.error("Failed to close all RabbitMQ Client resources", e);
   }
 }
 private void cleanup(int code, String message) {
   try {
     channel.close(code, message);
   } catch (Exception e) {
     logger.debug("failed to close channel on [{}]", e, message);
   }
   try {
     connection.close(code, message);
   } catch (Exception e) {
     logger.debug("failed to close connection on [{}]", e, message);
   }
 }
Exemplo n.º 23
0
    public void testRoutingInvalidRoutes() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        com.rabbitmq.client.Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("transient", false, false, false, null);
        connection.close();

        for (String dest : Arrays.asList("/exchange/missing", "/queue/transient", "/fruit/orange")) {
            routeInvalidSource(dest);
            routeInvalidTarget(dest);
        }
    }
Exemplo n.º 24
0
 private void destory() {
   try {
     if (null != channel) {
       channel.close();
     }
     if (null != connection) {
       connection.close();
     }
   } catch (IOException e) {
     log.error("Failed to close MQ connection: ", e);
   }
 }
Exemplo n.º 25
0
  public void shutdown() {
    run.set(false);
    synchronized (channel) {
      try {

        channel.close();
        connection.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 26
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();
  }
Exemplo n.º 27
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();
  }
Exemplo n.º 28
0
  /**
   * Remove RabbitReconnector if it's not null (to prevent reconnect). Close connection if it's not
   * null. Swallow IOExceptions.
   *
   * @param conn
   * @param reconnector
   */
  public static void closeConnectionAndRemoveReconnector(
      Connection conn, RabbitReconnector reconnector) {
    if (conn == null) {
      return;
    }

    if (reconnector != null) {
      conn.removeShutdownListener(reconnector);
    }

    try {
      conn.close();
    } catch (IOException e) {
      e.printStackTrace();
      // throw new RuntimeException(e);
    }
  }
Exemplo n.º 29
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 queueName = channel.queueDeclare().getQueue();

      if (argv.length < 1) {
        System.err.println("Usage: ReceiveLogsTopic [binding_key]...");
        System.exit(1);
      }

      for (String bindingKey : argv) {
        channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
      }

      System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

      QueueingConsumer consumer = new QueueingConsumer(channel);
      channel.basicConsume(queueName, true, consumer);

      while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());
        String routingKey = delivery.getEnvelope().getRoutingKey();

        System.out.println(" [x] Received '" + routingKey + "':'" + message + "'");
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (Exception ignore) {
        }
      }
    }
  }
Exemplo n.º 30
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();
  }