com.rabbitmq.client.DefaultConsumer Java Examples

The following examples show how to use com.rabbitmq.client.DefaultConsumer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MessageSubscriberFactory.java    From Insights with Apache License 2.0 6 votes vote down vote up
public void registerSubscriber(String routingKey, final EngineSubscriberResponseHandler responseHandler) throws Exception {
	Channel channel = connection.createChannel();
	String queueName = routingKey.replace(".", "_");
	channel.queueDeclare(queueName, true, false, false, null);
	channel.queueBind(queueName, MessageConstants.EXCHANGE_NAME, routingKey);
	channel.basicQos(ApplicationConfigProvider.getInstance().getMessageQueue().getPrefetchCount());
	responseHandler.setChannel(channel);
	log.debug("prefetchCount "+ApplicationConfigProvider.getInstance().getMessageQueue().getPrefetchCount() );
	Consumer consumer = new DefaultConsumer(channel) {
		@Override
		public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
				byte[] body) throws IOException {
			responseHandler.handleDelivery(consumerTag, envelope, properties, body);
		}
	};
	channel.basicConsume(queueName, false, routingKey, consumer);
}
 
Example #2
Source File: RpcTest.java    From util4j with Apache License 2.0 6 votes vote down vote up
public void init() throws Exception {
 //1、获取连接
    connection = RabbitMqConnectionFactoy.getConnection();
 //2、声明信道
 channel = connection.createChannel();
 //定义一个临时变量的接受队列名    
 replyQueueName = channel.queueDeclare().getQueue();
 DefaultConsumer consumer= new DefaultConsumer(channel) {
           @Override
           public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties,
                   byte[] body) throws IOException {
               //检查它的correlationId是否是我们所要找的那个
           	CompletableFuture<String> future=call.get(properties.getCorrelationId());
           	if(future!=null)
           	{
           		future.complete(new String(body,"UTF-8"));
           	}
           }
       };
 channel.basicConsume(replyQueueName, autoAck,consumer);
}
 
Example #3
Source File: ProducerExchangeConsumer_Fanout.java    From util4j with Apache License 2.0 6 votes vote down vote up
public void consumer1() throws Exception {
	//1、获取连接
       Connection connection =RabbitMqConnectionFactoy.getConnection();
       //2、声明通道
       Channel channel = connection.createChannel();
       //3、声明队列
       channel.queueDeclare(QUEUE_NAME1, false, false, false, null);
       //绑定队列到交换机
       channel.queueBind(QUEUE_NAME1, EXCHANGE_NAME, "");
       //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了)
       //channel.basicQos(1);//每次处理1个
       //4、定义队列的消费者
       //定义消费者
       DefaultConsumer consumer = new DefaultConsumer(channel) {
           @Override
           public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body)
                   throws IOException {
               //获取并转成String
               String message = new String(body, "UTF-8");
               System.out.println("-->消费者1号,收到消息,msg :"+message+",header:"+properties.getHeaders().toString());
               channel.basicAck(envelope.getDeliveryTag(), false);
           }
       };
       channel.basicConsume(QUEUE_NAME1, autoAck,consumer);
}
 
Example #4
Source File: ProducerExchangeConsumer_Direct.java    From util4j with Apache License 2.0 6 votes vote down vote up
public void consumer1() throws Exception {
	//1、获取连接
       Connection connection =RabbitMqConnectionFactoy.getConnection();
       //2、声明通道
       Channel channel = connection.createChannel();
       //3、声明队列
       channel.queueDeclare(QUEUE_NAME1, false, false, false, null);
       //绑定队列到交换机
       channel.queueBind(QUEUE_NAME1, EXCHANGE_NAME,ROUTER_KEY_1);
       //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了)
       //channel.basicQos(1);//每次处理1个
       //4、定义队列的消费者
       //定义消费者
       DefaultConsumer consumer = new DefaultConsumer(channel) {
           @Override
           public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body)
                   throws IOException {
               //获取并转成String
               String message = new String(body, "UTF-8");
               System.out.println("-->消费者1号,收到消息,msg :"+message+",header:"+properties.getHeaders().toString());
               channel.basicAck(envelope.getDeliveryTag(), false);
           }
       };
       channel.basicConsume(QUEUE_NAME1, autoAck,consumer);
}
 
Example #5
Source File: ProducerExchangeConsumer_Topic.java    From util4j with Apache License 2.0 6 votes vote down vote up
public void consumer1A() throws Exception {
	//1、获取连接
       Connection connection =RabbitMqConnectionFactoy.getConnection();
       //2、声明通道
       Channel channel = connection.createChannel();
       //3、声明队列
       channel.queueDeclare(QUEUE_NAME1, false, false, false, null);
       //绑定队列到交换机
       channel.queueBind(QUEUE_NAME1, EXCHANGE_NAME,"test.a");//只收到基数
       //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了)
       //channel.basicQos(1);//每次处理1个
       //4、定义队列的消费者
       //定义消费者
       DefaultConsumer consumer = new DefaultConsumer(channel) {
           @Override
           public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body)
                   throws IOException {
               //获取并转成String
               String message = new String(body, "UTF-8");
               System.out.println("-->消费者1A号,收到消息,msg :"+message+",header:"+properties.getHeaders().toString());
               channel.basicAck(envelope.getDeliveryTag(), false);
           }
       };
       channel.basicConsume(QUEUE_NAME1, autoAck,consumer);
}
 
Example #6
Source File: ProducerExchangeConsumer_Topic.java    From util4j with Apache License 2.0 6 votes vote down vote up
public void consumer1B() throws Exception {
	//1、获取连接
       Connection connection =RabbitMqConnectionFactoy.getConnection();
       //2、声明通道
       Channel channel = connection.createChannel();
       //3、声明队列
       channel.queueDeclare(QUEUE_NAME1, false, false, false, null);
       //绑定队列到交换机
       channel.queueBind(QUEUE_NAME1, EXCHANGE_NAME,"test.a");//只收到基数
       //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了)
       //channel.basicQos(1);//每次处理1个
       //4、定义队列的消费者
       //定义消费者
       DefaultConsumer consumer = new DefaultConsumer(channel) {
           @Override
           public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body)
                   throws IOException {
               //获取并转成String
               String message = new String(body, "UTF-8");
               System.out.println("-->消费者1B号,收到消息,msg :"+message+",header:"+properties.getHeaders().toString());
               channel.basicAck(envelope.getDeliveryTag(), false);
           }
       };
       channel.basicConsume(QUEUE_NAME1, autoAck,consumer);
}
 
Example #7
Source File: RabbitMQTopicUtil.java    From wangmarket with Apache License 2.0 6 votes vote down vote up
public void receive() throws IOException, TimeoutException{
      
       // 当声明队列,不加任何参数,产生的将是一个临时队列,getQueue返回的是队列名称
       String queueA = channel.queueDeclare().getQueue();
       System.out.println("临时队列:" + queueA);
       
       // 第三个参数为“绑定建”
       // * 可以代替一个单词。
       // # 可以替代零个或多个单词。
       channel.queueBind(queueA, EXCHANGE_NAME, "com.xnx3.wangmarket.default");
       Consumer consumerA = new DefaultConsumer(channel) {
           @Override
           public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
               String recv = new String(body, "UTF-8");
               System.out.println("Direct-Receive-A:" + recv);
           }
       };
       channel.basicConsume(queueA, true, consumerA);
}
 
Example #8
Source File: C.java    From java-study with Apache License 2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
		// 创建连接工厂
		ConnectionFactory factory = new ConnectionFactory();
//		设置RabbitMQ地址
		factory.setHost("127.0.0.1");
//		创建一个新的连接
		Connection connection = factory.newConnection();
//		创建一个频道
		Channel channel = connection.createChannel();
//		声明要关注的队列 -- 在RabbitMQ中,队列声明是幂等性的(一个幂等操作的特点是其任意多次执行所产生的影响均与一次执行的影响相同),也就是说,如果不存在,就创建,如果存在,不会对已经存在的队列产生任何影响。
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		System.out.println("C [*] Waiting for messages. To exit press CTRL+C");
//		DefaultConsumer类实现了Consumer接口,通过传入一个频道,告诉服务器我们需要那个频道的消息,如果频道中有消息,就会执行回调函数handleDelivery
		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("C [x] Received '" + message + "'");
			}
		};
//		自动回复队列应答 -- RabbitMQ中的消息确认机制
		channel.basicConsume(QUEUE_NAME, true, consumer);
	}
 
Example #9
Source File: RabbitMqConsumer.java    From flowing-retail-old with Apache License 2.0 6 votes vote down vote up
protected void connect() throws Exception {
  ConnectionFactory factory = new ConnectionFactory();
  factory.setHost("localhost");
  Connection connection = factory.newConnection();
  channel = connection.createChannel();

  String queueName = "flowing-retail-" + name;
  channel.queueDeclare(queueName, true, false, false, null);
  channel.exchangeDeclare(EXCHANGE_NAME, "fanout", true); // publish/subscribe model
  channel.queueBind(queueName, EXCHANGE_NAME, "*");

  System.out.println(" [*] Waiting for messages.");

  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 + "'");
      eventHandler.handleEvent(message);
    }
  };
  channel.basicConsume(queueName, true, consumer);
}
 
Example #10
Source File: ITRabbitMQSender.java    From zipkin-reporter-java with Apache License 2.0 6 votes vote down vote up
byte[] readMessage() throws Exception {
  final CountDownLatch countDown = new CountDownLatch(1);
  final AtomicReference<byte[]> result = new AtomicReference<>();

  // Don't close this as it invalidates the sender's connection!
  Channel channel = sender.localChannel();
  channel.basicConsume(sender.queue, true, new DefaultConsumer(channel) {
    @Override public void handleDelivery(String consumerTag, Envelope envelope,
        AMQP.BasicProperties properties, byte[] body) {
      result.set(body);
      countDown.countDown();
    }
  });
  assertThat(countDown.await(10, TimeUnit.SECONDS))
      .withFailMessage("Timed out waiting to read message")
      .isTrue();
  assertThat(result)
      .withFailMessage("handleDelivery set null body")
      .isNotNull();
  return result.get();
}
 
Example #11
Source File: RabbitMQSenderBenchmarks.java    From zipkin-reporter-java with Apache License 2.0 6 votes vote down vote up
@Override protected Sender createSender() throws Exception {
  RabbitMQSender result = RabbitMQSender.newBuilder()
      .queue("zipkin-jmh")
      .addresses("localhost:5672").build();

  CheckResult check = result.check();
  if (!check.ok()) {
    throw new AssumptionViolatedException(check.error().getMessage(), check.error());
  }

  channel = result.localChannel();
  channel.queueDelete(result.queue);
  channel.queueDeclare(result.queue, false, true, true, null);

  Thread.sleep(500L);

  new Thread(() -> {
    try {
      channel.basicConsume(result.queue, true, new DefaultConsumer(channel));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }).start();

  return result;
}
 
Example #12
Source File: TestClient.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
public static void main(String[] args) {
  CountDownLatch countDown = new CountDownLatch(1);
  ConnectionFactory factory = new ConnectionFactory();
  factory.setUsername("guest");
  factory.setPassword("guest");
  factory.setHost("127.0.0.1");
  try (Connection con = factory.newConnection(); Channel chn = con.createChannel()) {
    AtomicLong receivedMessages = new AtomicLong();
    String consumerTag =
        chn.basicConsume("product.catalog_item.sync", true, new DefaultConsumer(chn) {
          @Override
          public void handleDelivery(String tag, Envelope envelope, BasicProperties properties,
              byte[] body) throws IOException {
            long actualCount = receivedMessages.incrementAndGet();
            if (actualCount % 1000 == 0) {
              System.out.println("Received " + actualCount + " messages so far.");
            }
            // countDown.countDown();
          }
        });
    System.out.println(consumerTag);
    countDown.await();
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example #13
Source File: ComplexUseCasesTests.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void multiple_expired_messages_are_not_delivered_to_consumer() throws IOException, TimeoutException, InterruptedException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            queue("fruits").withMessageTtl(-1L).declare(channel);

            List<String> messages = new ArrayList<>();
            channel.basicConsume("fruits", new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body) {
                    messages.add(new String(body));
                }
            });

            channel.basicPublish("", "fruits", null, "banana".getBytes());
            channel.basicPublish("", "fruits", null, "orange".getBytes());
            TimeUnit.MILLISECONDS.sleep(100L);
            assertThat(messages).hasSize(0);
        }
    }
}
 
Example #14
Source File: ComplexUseCasesTests.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void expired_message_should_be_consumable_after_being_dead_lettered() throws IOException, TimeoutException, InterruptedException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            channel.exchangeDeclare("rejected-ex", BuiltinExchangeType.FANOUT);
            channel.queueDeclare("rejected", true, false, false, null);
            channel.queueBindNoWait("rejected", "rejected-ex", "unused", null);
            queue("fruits").withMessageTtl(10L).withDeadLetterExchange("rejected-ex").declare(channel);

            List<String> messages = new ArrayList<>();
            channel.basicConsume("rejected", new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body) {
                    messages.add(new String(body));
                }
            });

            channel.basicPublish("", "fruits", null, "banana".getBytes());
            TimeUnit.MILLISECONDS.sleep(100L);
            assertThat(messages).hasSize(1);
        }
    }
}
 
Example #15
Source File: AMQPConsumer.java    From nifi with Apache License 2.0 5 votes vote down vote up
AMQPConsumer(final Connection connection, final String queueName, final boolean autoAcknowledge) throws IOException {
    super(connection);
    this.validateStringProperty("queueName", queueName);
    this.queueName = queueName;
    this.autoAcknowledge = autoAcknowledge;
    this.responseQueue = new LinkedBlockingQueue<>(10);

    logger.info("Successfully connected AMQPConsumer to " + connection.toString() + " and '" + queueName + "' queue");

    final Channel channel = getChannel();
    consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(final String consumerTag, final Envelope envelope, final BasicProperties properties, final byte[] body) throws IOException {
            if (!autoAcknowledge && closed) {
                channel.basicReject(envelope.getDeliveryTag(), true);
                return;
            }

            try {
                responseQueue.put(new GetResponse(envelope, properties, body, Integer.MAX_VALUE));
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    };

    channel.basicConsume(queueName, autoAcknowledge, consumer);
}
 
Example #16
Source File: MessageService.java    From cukes with Apache License 2.0 5 votes vote down vote up
@SneakyThrows({IOException.class, InterruptedException.class})
public MessageWrapper receiveMessage(String queue, int timeoutInSeconds) {
    Channel channel = connectionService.getChannel();
    BlockingQueue<MessageWrapper> result = new ArrayBlockingQueue<MessageWrapper>(1);
    channel.basicConsume(queue, true, new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
            String response = new String(body);
            MessageWrapper messageWrapper = new MessageWrapper(response, properties);
            result.add(messageWrapper);
        }
    });
    return result.poll(timeoutInSeconds, TimeUnit.SECONDS);
}
 
Example #17
Source File: ProducerConsumer.java    From util4j with Apache License 2.0 5 votes vote down vote up
public void consumer1() throws Exception {
		//1、获取连接
        Connection connection =RabbitMqConnectionFactoy.getConnection();
        //2、声明通道
        Channel channel = connection.createChannel();
        //3、声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了)
        channel.basicQos(1);//每次处理1个
        //4、定义队列的消费者
        //定义消费者
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body)
                    throws IOException {
                //获取并转成String
                String message = new String(body, "UTF-8");
                System.out.println("-->消费者1号,收到消息,msg :"+message+",header:"+properties.getHeaders().toString());
                /**
                 *     basicAck:成功消费,消息从队列中删除 
					   basicNack:requeue=true,消息重新进入队列,false被删除 
					   basicReject:等同于basicNack 
					   basicRecover:消息重入队列,requeue=true,发送给新的consumer,false发送给相同的consumer 
                 */
//                channel.basicAck(envelope.getDeliveryTag(), false);
//                channel.basicReject(envelope.getDeliveryTag(), false);//拒绝此条消息,并重发到队列(可能再次受到此消息)
//                channel.basicRecover(true);//消息重发给其它消费者
                channel.basicNack(envelope.getDeliveryTag(), false, false);
            }
        };
        channel.basicConsume(QUEUE_NAME, autoAck,consumer);
	}
 
Example #18
Source File: IntegrationTest.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@Test
void basic_consume_case() throws IOException, TimeoutException, InterruptedException {
    String exchangeName = "test-exchange";
    String routingKey = "test.key";

    try (Connection conn = new MockConnectionFactory().newConnection()) {
        assertThat(conn).isInstanceOf(MockConnection.class);

        try (Channel channel = conn.createChannel()) {
            assertThat(channel).isInstanceOf(MockChannel.class);

            channel.exchangeDeclare(exchangeName, "direct", true);
            String queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, exchangeName, routingKey);

            List<String> messages = new ArrayList<>();
            channel.basicConsume(queueName, false, "myConsumerTag",
                new DefaultConsumer(channel) {
                    @Override
                    public void handleDelivery(String consumerTag,
                                               Envelope envelope,
                                               AMQP.BasicProperties properties,
                                               byte[] body) throws IOException {
                        long deliveryTag = envelope.getDeliveryTag();
                        messages.add(new String(body));
                        // (process the message components here ...)
                        channel.basicAck(deliveryTag, false);
                    }
                });

            byte[] messageBodyBytes = "Hello, world!".getBytes();
            channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

            TimeUnit.MILLISECONDS.sleep(200L);

            assertThat(messages).containsExactly("Hello, world!");
        }
    }
}
 
Example #19
Source File: RpcTest.java    From util4j with Apache License 2.0 5 votes vote down vote up
public void rpcServer() throws Exception {
 	//1、获取连接
       Connection connection = RabbitMqConnectionFactoy.getConnection();
       //2、声明信道
       Channel channel = connection.createChannel();
       //3、声明队列
       channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
       channel.basicQos(1);
       DefaultConsumer consumer = new DefaultConsumer(channel) {
           @Override
           public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body)
                   throws IOException {
               //获取并转成String
               String message = new String(body, "UTF-8");
               String cid=properties.getCorrelationId();
               System.out.println("server-->收到消息,msg :"+message+",cid:"+cid);
               String rsp=message+" rsp";
               // 返回处理结果队列
                  channel.basicPublish("", properties.getReplyTo(), properties,rsp.getBytes("UTF-8"));
                  //  确认消息,已经收到后面参数 multiple:是否批量.true:将一次性确认所有小于envelope.getDeliveryTag()的消息。
                  channel.basicAck(envelope.getDeliveryTag(), false);
           }
       };
       channel.basicConsume(RPC_QUEUE_NAME, autoAck,consumer);
       Thread.sleep(1000000);
       //6、关闭通道
       channel.close();
       //7、关闭连接
       connection.close();
}
 
Example #20
Source File: PositiveQueueDeleteTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Test (dataProvider = "queueNames")
public void testDeleteUsedQueue(String queueName) throws Exception {
    channel.queueDeclare(queueName, false, false, false, null);
    channel.basicConsume(queueName, new DefaultConsumer(channel));

    AMQP.Queue.DeleteOk deleteOk = channel.queueDelete(queueName, false, true);
    Assert.assertEquals(deleteOk.getMessageCount(), 0);
}
 
Example #21
Source File: NegativeQueuePurgeTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Test(description = "Test queue purge on a queue with consumers", expectedExceptions = IOException.class)
public void deleteUsedQueue() throws Exception {
    String queueName = "NegativeQueuePurgeTestDeleteUsedQueue";
    Channel channel = amqpConnection.createChannel();

    channel.queueDeclare(queueName, false, false, false, null);
    channel.basicConsume(queueName, new DefaultConsumer(channel));

    channel.queuePurge(queueName);
}
 
Example #22
Source File: NegativeQueueDeleteTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Test(description = "Test queue auto delete", expectedExceptions = IOException.class)
public void testQueueAutoDelete() throws Exception {
    Channel channel = amqpConnection.createChannel();

    String queueName = "NegativeQueueDeleteTestTestQueueAutoDelete";
    channel.queueDeclare(queueName, false, false, true, null);
    String consumerTag = channel.basicConsume(queueName, new DefaultConsumer(channel));

    channel.basicCancel(consumerTag);

    // This should throw an exception since the queue is auto deleted
    channel.queueDeclarePassive(queueName);
}
 
Example #23
Source File: NegativeQueueDeleteTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Parameters({"broker-hostname", "broker-port", "admin-username", "admin-password"})
@BeforeMethod
public void setUp(String hostname, String port, String username, String password) throws Exception {
    amqpConnection = ClientHelper.getAmqpConnection(username, password, hostname, port);
    Channel channel = amqpConnection.createChannel();

    channel.queueDeclare(queueWithConsumers, false, false, false, null);
    channel.queueDeclare(queueWithMessages, false, false, false, null);

    channel.basicConsume(queueWithConsumers, new DefaultConsumer(channel));
    channel.basicPublish("<<default>>", queueWithMessages,
                         new AMQP.BasicProperties(), "Test Message".getBytes());
}
 
Example #24
Source File: RabbitMQTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void basicConsume(final MockTracer tracer) throws IOException, InterruptedException {
  final String exchangeName = "basicConsumeExchange";
  final String queueName = "basicConsumeQueue";
  final String routingKey = "#";

  channel.exchangeDeclare(exchangeName, "direct", true);
  channel.queueDeclare(queueName, true, false, false, null);
  channel.queueBind(queueName, exchangeName, routingKey);

  final byte[] messageBodyBytes = "Hello, world!".getBytes();
  channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

  final CountDownLatch latch = new CountDownLatch(1);
  channel.basicConsume(queueName, false, new DefaultConsumer(channel) {
    @Override
    public void handleDelivery(final String consumerTag, final Envelope envelope, final AMQP.BasicProperties properties, final byte[] body) throws IOException {
      final long deliveryTag = envelope.getDeliveryTag();
      channel.basicAck(deliveryTag, false);
      latch.countDown();
    }
  });

  latch.await(15, TimeUnit.SECONDS);
  List<MockSpan> finishedSpans = tracer.finishedSpans();
  for (int tries = 10; tries > 0 && finishedSpans.size() < 2; --tries) {
    TimeUnit.SECONDS.sleep(1L);
    finishedSpans = tracer.finishedSpans();
  }

  assertEquals(2, finishedSpans.size());
  assertNull(tracer.activeSpan());
}
 
Example #25
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@Test
void rpcClient() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {

            String queue = channel.queueDeclare().getQueue();
            channel.basicConsume(queue, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    channel.basicPublish(
                        "",
                        properties.getReplyTo(),
                        MessageProperties.BASIC.builder().correlationId(properties.getCorrelationId()).build(), "pong".getBytes()
                    );
                }
            });

            RpcClientParams params = new RpcClientParams();
            params.channel(channel);
            params.exchange("");
            params.routingKey(queue);
            RpcClient client = new RpcClient(params);
            RpcClient.Response response = client.responseCall("ping".getBytes());
            assertThat(response.getBody()).isEqualTo("pong".getBytes());
        }
    }
}
 
Example #26
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@RepeatedTest(31)
void basicConsume_concurrent_queue_access() throws IOException, TimeoutException, InterruptedException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            String queueName = channel.queueDeclare().getQueue();

            BlockingQueue<String> messages = new LinkedBlockingQueue<>();
            channel.basicConsume("", new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body) {
                    messages.offer(new String(body));
                }
            });

            int totalMessages = 101;
            for (int i = 1; i <= totalMessages; i++) {
                channel.basicPublish("", queueName, null, "test message".getBytes());
            }
            for (int i = 1; i <= totalMessages; i++) {
                assertThat(messages.poll(200L, TimeUnit.MILLISECONDS)).isNotNull();
            }
        }
    }
}
 
Example #27
Source File: ComplexUseCasesTests.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@Test
void closing_one_connection_does_not_cancel_consumers_defined_within_another_one() throws InterruptedException {
    MockConnectionFactory connectionFactory = new MockConnectionFactory();
    try (MockConnection conn = connectionFactory.newConnection()) {
        try (MockChannel channel = conn.createChannel()) {
            queue("numbers").declare(channel);

            List<String> messages = new ArrayList<>();
            Semaphore deliveries = new Semaphore(-2);

            channel.basicConsume("numbers", new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body) {
                    messages.add(new String(body));
                    deliveries.release();
                }
            });

            connectionFactory.newConnection().close();

            try (MockConnection conn2 = connectionFactory.newConnection()) {
                try (MockChannel channel2 = conn.createChannel()) {
                    Arrays.asList("one", "two", "three").stream().forEach(message ->
                        channel2.basicPublish("", "numbers", null, message.getBytes())
                    );
                }
            }

            assertThat(deliveries.tryAcquire(1, TimeUnit.SECONDS)).as("Messages have been delivered").isTrue();

            assertThat(messages).containsExactly("one", "two", "three");
        }
    }
}
 
Example #28
Source File: ComplexUseCasesTests.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@Test
void can_consume_messages_published_in_a_previous_connection() throws InterruptedException {
    MockConnectionFactory connectionFactory = new MockConnectionFactory();
    try (MockConnection conn = connectionFactory.newConnection()) {
        try (MockChannel channel = conn.createChannel()) {
            queue("numbers").declare(channel);
            Arrays.asList("one", "two", "three").stream().forEach(message ->
                channel.basicPublish("", "numbers", null, message.getBytes())
            );
        }
    }

    try (MockConnection conn = connectionFactory.newConnection()) {
        try (MockChannel channel = conn.createChannel()) {

            List<String> messages = new ArrayList<>();
            Semaphore deliveries = new Semaphore(-2);

            channel.basicConsume("numbers", new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body) {
                    messages.add(new String(body));
                    deliveries.release();
                }
            });

            assertThat(deliveries.tryAcquire(1, TimeUnit.SECONDS)).as("Messages have been delivered").isTrue();

            assertThat(messages).containsExactly("one", "two", "three");
        }
    }
}
 
Example #29
Source File: IntegrationTest.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@Test
void redelivered_message_should_have_redelivery_marked_as_true() throws IOException, TimeoutException, InterruptedException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        CountDownLatch messagesToBeProcessed = new CountDownLatch(2);
        try (Channel channel = conn.createChannel()) {
            queue("fruits").declare(channel);
            AtomicReference<Envelope> redeliveredMessageEnvelope = new AtomicReference();

            channel.basicConsume("fruits", new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body) {
                    if(messagesToBeProcessed.getCount() == 1){
                        redeliveredMessageEnvelope.set(envelope);
                        runAndEatExceptions(messagesToBeProcessed::countDown);

                    }else{
                        runAndEatExceptions(() -> channel.basicNack(envelope.getDeliveryTag(), false, true));
                        runAndEatExceptions(messagesToBeProcessed::countDown);
                    }

                }
            });

            channel.basicPublish("", "fruits", null, "banana".getBytes());

            final boolean finishedProperly = messagesToBeProcessed.await(1000, TimeUnit.SECONDS);
            assertThat(finishedProperly).isTrue();
            assertThat(redeliveredMessageEnvelope.get()).isNotNull();
            assertThat(redeliveredMessageEnvelope.get().isRedeliver()).isTrue();
        }
    }
}
 
Example #30
Source File: ExtensionTest.java    From rabbitmq-mock with Apache License 2.0 4 votes vote down vote up
@Test
void check_xdeath_header_count_increments_for_the_same_q_and_reason() throws IOException, TimeoutException, InterruptedException {
    try (MockConnection conn = new MockConnectionFactory().newConnection()) {
        try (MockChannel channel = conn.createChannel()) {

            Semaphore se = new Semaphore(0);

            QueueDeclarator.queue("timed").withMessageTtl(1L).withDeadLetterExchange("rejected-ex").declare(channel);
            QueueDeclarator.queue("fruits").withDeadLetterExchange("rejected-ex").declare(channel);
            channel.exchangeDeclare("rejected-ex", BuiltinExchangeType.FANOUT);
            channel.queueBindNoWait("fruits", "rejected-ex", "unused", null);

            AtomicInteger nackCounter = new AtomicInteger();
            AtomicReference<AMQP.BasicProperties> messagePropertiesAfterMultipleReject = new AtomicReference<>();

            channel.basicConsume("fruits", new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body) {
                    if (nackCounter.incrementAndGet() <= 4) {
                        channel.basicNack(envelope.getDeliveryTag(), false, false);
                    } else {
                        channel.basicAck(envelope.getDeliveryTag(), false);
                        messagePropertiesAfterMultipleReject.set(properties);
                        se.release();
                    }
                }
            });

            channel.basicPublish("", "timed", null, "banana".getBytes());

            se.acquire();

            assertThat(messagePropertiesAfterMultipleReject.get().getHeaders()).containsKey("x-death");
            List<Map<String, Object>> xDeathHeader = (List<Map<String, Object>>) messagePropertiesAfterMultipleReject.get().getHeaders().get("x-death");
            assertThat(xDeathHeader).hasSize(2);
            assertThat(xDeathHeader.get(0))
                .containsEntry("queue", "fruits")
                .containsEntry("reason", "rejected")
                .containsEntry("exchange", "rejected-ex")
                .containsEntry("routing-keys", Collections.singletonList("timed"))
                .containsEntry("count", 4L)
            ;
            assertThat(xDeathHeader.get(1))
                .containsEntry("queue", "timed")
                .containsEntry("reason", "expired")
                .containsEntry("exchange", "")
                .containsEntry("routing-keys", Collections.singletonList("timed"))
                .containsEntry("count", 1L)
            ;
        }
    }
}