コード例 #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();
    }
  }
コード例 #2
0
  protected Map<String, Channel> initChannel(
      Connection connection, int assignedNum, String queueName) throws IOException {
    Channel consumerChannel = connection.createChannel();
    Channel publisherChannel = connection.createChannel();

    Map<String, Channel> result = new HashMap<String, Channel>();

    if (consumerChannel != null && !consumerChannel.isOpen()) {

      consumerChannel = connection.createChannel();
    }
    if (publisherChannel != null && !publisherChannel.isOpen()) {
      publisherChannel = connection.createChannel();
    }

    DecimalFormat formatter = new DecimalFormat("#00.###");

    String queueRoutingKey = CONSUMER_ROUTING_KEY + formatter.format(assignedNum);

    consumerChannel.queueDeclare(queueName, false, false, true, null);
    consumerChannel.exchangeDeclare(CONSUMER_EXCHANGE_NAME, CONSUMER_EXCHANGE_TYPE, false);
    consumerChannel.queueBind(queueName, CONSUMER_EXCHANGE_NAME, queueRoutingKey);
    consumerChannel.basicQos(1);
    publisherChannel.exchangeDeclare(PUBLISHER_EXCHANGE_NAME, PUBLISHER_EXCHANGE_TYPE, false);
    result.put("consumer", consumerChannel);
    result.put("publisher", publisherChannel);
    return result;
  }
コード例 #3
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);
 }
コード例 #4
0
 public void testDeclarationOfManyAutoDeleteExchangesWithTransientExchangesThatAreDeleted()
     throws IOException, TimeoutException {
   Channel ch = connection.createChannel();
   assertRecordedExchanges(connection, 0);
   for (int i = 0; i < 5000; i++) {
     String src = "src-" + UUID.randomUUID().toString();
     String dest = "dest-" + UUID.randomUUID().toString();
     ch.exchangeDeclare(src, "fanout", false, true, null);
     ch.exchangeDeclare(dest, "fanout", false, true, null);
     ch.exchangeBind(dest, src, "doesn't matter");
     ch.exchangeDelete(dest);
   }
   assertRecordedExchanges(connection, 0);
   ch.close();
 }
コード例 #5
0
 public void publishTopics(List<String> topics) throws IOException, TimeoutException {
   for (String topic : topics) {
     Channel channel = connection.createChannel();
     addChannels(topic, channel);
     channel.exchangeDeclare(topic, "fanout");
   }
 }
コード例 #6
0
ファイル: AmqpConsumer.java プロジェクト: yizhou136/myeyes
  public static void t1() throws Exception {
    Channel channel = generateChannel();
    // channel.exchangeDeclare(TestAmqp.ExchangerName, "direct", true, false, null);
    // channel.exchangeDeclare(TestAmqp.FanoutExchangerName, "fanout", true, false, null);
    channel.exchangeDeclare(TestAmqp.TopicExchangerName, "topic", false, false, null);
    channel.queueDeclare(TestAmqp.TopicQueueName, false, false, false, null);
    // channel.queueBind(TestAmqp.TopicQueueName, TestAmqp.TopicExchangerName,
    // TestAmqp.RouteingName);
    // channel.queueBind(TestAmqp.TopicQueueName, TestAmqp.TopicExchangerName, "*");
    channel.queueBind(TestAmqp.TopicQueueName, TestAmqp.TopicExchangerName, "#.*");

    // channel.basicPublish(TestAmqp.ExchangerName, TestAmqp.RouteingName, null, "haha".getBytes());

    QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

    channel.basicQos(1);
    channel.basicConsume(TestAmqp.TopicQueueName, queueingConsumer);

    while (true) {
      QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
      System.out.println(new String(delivery.getBody()));

      long deliveryTag = delivery.getEnvelope().getDeliveryTag();
      System.out.println("start basicAck:" + deliveryTag);
      // if (true)throw new RuntimeException("xxxxx");
      channel.basicAck(deliveryTag, false);
    }

    // channel.close();
    // connection.close();
  }
コード例 #7
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) {
        }
      }
    }
  }
コード例 #8
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();
  }
コード例 #9
0
  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().");
  }
コード例 #10
0
ファイル: ReceiveLogs.java プロジェクト: skambc/garden
  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("10.71.49.228");
    factory.setUsername("jinhd");
    factory.setPassword("admin");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, "");

    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 '" + message + "'");
          }
        };
    channel.basicConsume(queueName, true, consumer);
  }
コード例 #11
0
  public static void main(String[] argv)
      throws java.io.IOException, java.lang.InterruptedException, TimeoutException {
    // 创建连接和频道
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    // 声明direct类型转发器
    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    String queueName = channel.queueDeclare().getQueue();
    String severity = getSeverity();
    // 指定binding_key
    channel.queueBind(queueName, EXCHANGE_NAME, severity);
    System.out.println(" [*] Waiting for " + severity + " logs. 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());

      System.out.println(" [x] Received '" + message + "'");
    }
  }
コード例 #12
0
ファイル: Work.java プロジェクト: JavaLuSir/MyDemo
  public static void main(String[] args) throws IOException, TimeoutException {

    ConnectionFactory factory = new ConnectionFactory();

    factory.setHost("localhost");

    Connection connection = factory.newConnection();

    Channel channel = connection.createChannel();

    channel.exchangeDeclare(Work.EXCHANGE_NAME, "fanout");

    String randomQueName = channel.queueDeclare().getQueue();

    channel.queueBind(randomQueName, Work.EXCHANGE_NAME, "");

    // channel.queueDeclare(QUEUE_NAME, true, false, false, null);

    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 '" + message + "'" + Thread.currentThread().getName());
          }
        };

    channel.basicConsume(randomQueName, true, consumer);
  }
コード例 #13
0
  public static void main(String[] arg) throws IOException, InterruptedException {

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

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

    if (arg.length < 1) {
      System.err.println("Usage: ReceiveLogsDirect [info] [warning] [error]");
      System.exit(1);
    }

    for (String severity : arg) {
      channel.queueBind(queueName, EXCHANGE_NAME, severity);
    }

    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 + "'");
    }
  }
コード例 #14
0
ファイル: Consumer.java プロジェクト: wq012176/Spring-Engine
  public static void main(String[] args) throws IOException, InterruptedException {
    Random random = new Random();
    int i = random.nextInt(10);
    String clientName = "client-" + i;

    Channel channel = RabbitUtil.getChannel();
    // 申明交换器
    channel.exchangeDeclare(C.FANOUT_EXCHANGE, "fanout");

    // 匿名队列
    String queueName = channel.queueDeclare().getQueue();
    System.err.println("queueName:" + queueName);

    // 绑定队列到交换器
    AMQP.Queue.BindOk bindOk = channel.queueBind(queueName, C.FANOUT_EXCHANGE, "");
    System.err.println("bindOk:" + bindOk);

    System.out.println(clientName + "  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());

      System.out.println(clientName + " Received :" + message + "");
      Thread.sleep(1000);
    }
  }
コード例 #15
0
  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();
    }
  }
コード例 #16
0
  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();
    }
  }
コード例 #17
0
  @Override
  public boolean subscribeToChannel(String exchangeName, String type) {
    if (!connected) {
      return false;
    }
    try {
      // we create a new channel
      Channel channel = connection.createChannel();
      channel.exchangeDeclare(exchangeName, type);
      String queueName = channel.queueDeclare().getQueue();
      channel.queueBind(queueName, exchangeName, "");

      // we define what happens if we recieve a new Message
      channel.basicConsume(queueName, new RabbitMQConsumer(channel, service));
      subscribedChannels.putIfAbsent(exchangeName, channel);
      Log.i(
          LOGTAG,
          "subscribed to "
              + subscribedChannels.size()
              + " Channels"
              + "\n"
              + "started subscribtion to : "
              + exchangeName);
      return true;
    } catch (Exception e) {
      Log.e(LOGTAG, "Connection Problem at subscribeToChannel(): " + e.toString());
    }
    return false;
  }
コード例 #18
0
 public void connect() {
   ConnectionFactory factory = new ConnectionFactory();
   try {
     factory.setUsername("guest");
     factory.setPassword("guest");
     factory.setVirtualHost("/");
     factory.setHost("localhost");
     factory.setPort(5672);
     conn = factory.newConnection();
     channel = conn.createChannel();
     String exchangeName = "exchange." + Math.abs((new Random()).nextInt());
     String queueName = "queue";
     String routingKey = "route";
     boolean durable = true;
     channel.exchangeDeclare(exchangeName, "topic", durable);
     channel.queueDeclare(queueName, durable, false, false, null);
     channel.queueBind(queueName, exchangeName, routingKey);
     consumer = new QueueingConsumer(channel);
     channel.basicConsume(queueName, false, consumer);
   } catch (IOException e) {
     e.printStackTrace();
   } catch (TimeoutException e) {
     e.printStackTrace();
   }
 }
コード例 #19
0
 private void declareExchange(
     final Channel channel,
     final String exchange,
     final String exchangeType,
     final Map<String, Object> exchangeArgs)
     throws IOException {
   channel.exchangeDeclare(
       exchange, exchangeType, endpoint.isDurable(), endpoint.isAutoDelete(), exchangeArgs);
 }
コード例 #20
0
 private void expectAutoDeleteQueueAndBindingRecovery(Channel ch, String x, String q)
     throws IOException, InterruptedException, TimeoutException {
   ch.confirmSelect();
   ch.queuePurge(q);
   AMQP.Queue.DeclareOk ok1 = declareClientNamedAutoDeleteQueue(ch, q);
   assertEquals(0, ok1.getMessageCount());
   ch.exchangeDeclare(x, "fanout");
   ch.basicPublish(x, "", null, "msg".getBytes());
   waitForConfirms(ch);
   AMQP.Queue.DeclareOk ok2 = declareClientNamedAutoDeleteQueue(ch, q);
   assertEquals(1, ok2.getMessageCount());
 }
コード例 #21
0
 // bug 26552
 public void testClientNamedTransientAutoDeleteQueueAndBindingRecovery()
     throws IOException, InterruptedException, TimeoutException {
   String q = UUID.randomUUID().toString();
   String x = "tmp-fanout";
   Channel ch = connection.createChannel();
   ch.queueDelete(q);
   ch.exchangeDelete(x);
   ch.exchangeDeclare(x, "fanout");
   ch.queueDeclare(q, false, false, true, null);
   ch.queueBind(q, x, "");
   restartPrimaryAndWaitForRecovery();
   expectChannelRecovery(ch);
   ch.confirmSelect();
   ch.queuePurge(q);
   ch.exchangeDeclare(x, "fanout");
   ch.basicPublish(x, "", null, "msg".getBytes());
   waitForConfirms(ch);
   AMQP.Queue.DeclareOk ok = ch.queueDeclare(q, false, false, true, null);
   assertEquals(1, ok.getMessageCount());
   ch.queueDelete(q);
   ch.exchangeDelete(x);
 }
コード例 #22
0
 public void testDeclarationOfManyAutoDeleteExchangesWithTransientQueuesThatAreDeleted()
     throws IOException, TimeoutException {
   Channel ch = connection.createChannel();
   assertRecordedExchanges(connection, 0);
   for (int i = 0; i < 5000; i++) {
     String x = UUID.randomUUID().toString();
     ch.exchangeDeclare(x, "fanout", false, true, null);
     String q = ch.queueDeclare().getQueue();
     ch.queueBind(q, x, "doesn't matter");
     ch.queueDelete(q);
   }
   assertRecordedExchanges(connection, 0);
   ch.close();
 }
コード例 #23
0
  public void connect() throws Exception {
    if (conn != null) disconnect();

    int offset = ++cidx % factory.length;
    logger.info("AMQP connect to " + this.hostName[offset]);
    conn = factory[offset].newConnection();

    if (conn == null) throw new Exception("connection failed");

    channel = conn.createChannel();

    boolean internal = false, durable = true, autoDelete = false;
    channel.exchangeDeclare(getAlertExchangeName(), "topic", durable, autoDelete, internal, null);
  }
コード例 #24
0
ファイル: RabbitMQEndpoint.java プロジェクト: norbertk7/camel
  /** If needed, declare Exchange, declare Queue and bind them with Routing Key */
  public void declareExchangeAndQueue(Channel channel) throws IOException {
    Map<String, Object> queueArgs = new HashMap<String, Object>();
    Map<String, Object> exchangeArgs = new HashMap<String, Object>();

    if (deadLetterExchange != null) {
      queueArgs.put(RabbitMQConstants.RABBITMQ_DEAD_LETTER_EXCHANGE, getDeadLetterExchange());
      queueArgs.put(RabbitMQConstants.RABBITMQ_DEAD_LETTER_ROUTING_KEY, getDeadLetterRoutingKey());
      // TODO Do we need to setup the args for the DeadLetter?
      channel.exchangeDeclare(
          getDeadLetterExchange(),
          getDeadLetterExchangeType(),
          isDurable(),
          isAutoDelete(),
          new HashMap<String, Object>());
      channel.queueDeclare(getDeadLetterQueue(), isDurable(), false, isAutoDelete(), null);
      channel.queueBind(
          getDeadLetterQueue(),
          getDeadLetterExchange(),
          getDeadLetterRoutingKey() == null ? "" : getDeadLetterRoutingKey());
    }

    if (getQueueArgsConfigurer() != null) {
      getQueueArgsConfigurer().configurArgs(queueArgs);
    }
    if (getExchangeArgsConfigurer() != null) {
      getExchangeArgsConfigurer().configurArgs(exchangeArgs);
    }

    channel.exchangeDeclare(
        getExchangeName(), getExchangeType(), isDurable(), isAutoDelete(), exchangeArgs);
    if (getQueue() != null) {
      // need to make sure the queueDeclare is same with the exchange declare
      channel.queueDeclare(getQueue(), isDurable(), false, isAutoDelete(), queueArgs);
      channel.queueBind(
          getQueue(), getExchangeName(), getRoutingKey() == null ? "" : getRoutingKey());
    }
  }
コード例 #25
0
 public void testClientNamedQueueBindingRecovery()
     throws IOException, InterruptedException, TimeoutException {
   String q = "java-client.test.recovery.q2";
   String x = "tmp-fanout";
   Channel ch = connection.createChannel();
   ch.queueDelete(q);
   ch.exchangeDelete(x);
   ch.exchangeDeclare(x, "fanout");
   declareClientNamedAutoDeleteQueue(ch, q);
   ch.queueBind(q, x, "");
   closeAndWaitForRecovery();
   expectChannelRecovery(ch);
   expectAutoDeleteQueueAndBindingRecovery(ch, x, q);
   ch.queueDelete(q);
   ch.exchangeDelete(x);
 }
コード例 #26
0
 void autoCreateAndBind(
     String exchange,
     String exchangeType,
     String queue,
     String routingKey,
     boolean isPoisonQueueEnabled)
     throws IOException {
   // Creates durable non-autodeleted exchange and queue(s).
   channel.exchangeDeclare(exchange, exchangeType, true);
   channel.queueDeclare(queue, true, false, false, null);
   channel.queueBind(queue, exchange, routingKey);
   if (isPoisonQueueEnabled) {
     String poisonQueue = queue + POISON;
     channel.queueDeclare(poisonQueue, true, false, false, null);
     channel.queueBind(poisonQueue, exchange, routingKey + POISON);
   }
 }
コード例 #27
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) {
        }
      }
    }
  }
コード例 #28
0
ファイル: Producer.java プロジェクト: 354447958/test
  public Producer(String exchangeName) {
    try {
      // 初始化
      this.exchangeName = exchangeName;
      ConnectionFactory factory = new ConnectionFactory();
      factory.setHost(Config.HOST);
      //		factory.setPort(5672);
      //		factory.setUsername("guest");
      //		factory.setPassword("guest");
      connection = factory.newConnection();
      channel = connection.createChannel();

      // 声明一个fanout类型的exchange
      channel.exchangeDeclare(exchangeName, "fanout");
    } catch (IOException | TimeoutException e) {
      e.printStackTrace();
    }
  }
コード例 #29
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();
  }
コード例 #30
0
ファイル: Server.java プロジェクト: FFng/sourcecode
  public Server init() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("rpc_user");
    factory.setPassword("rpcme");
    connection = factory.newConnection();
    channel = connection.createChannel();

    channel.exchangeDeclare("rpc", "direct");
    channel.queueDeclare("ping", false, false, false, null);
    channel.queueBind("ping", "rpc", "ping");

    consumer = new QueueingConsumer(channel);
    channel.basicConsume("ping", false, "ping", consumer);

    System.out.println("Waiting for RPC calls...");

    return this;
  }