com.rabbitmq.client.MessageProperties Java Examples

The following examples show how to use com.rabbitmq.client.MessageProperties. 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: NewTask.java    From java-study with Apache License 2.0 7 votes vote down vote up
public static void main(String[] argv) throws Exception {
	// 创建工厂类
	ConnectionFactory factory = new ConnectionFactory();
	//factory.setHost("localhost");
	factory.setUri("amqp://guest:[email protected]:5672");
	Connection connection = factory.newConnection();
	Channel channel = connection.createChannel();

	channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
	 Map map=new HashMap();  
        map.put("aa", 11);
        map.put("bb", 22);
        map.put("cc", 33);
	String message = getMessage(argv);

	channel.basicPublish("", TASK_QUEUE_NAME,
			MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
	System.out.println(" [x] Sent '" + message + "'");

	channel.close();
	connection.close();
}
 
Example #2
Source File: NewTask.java    From rabbitmq with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws java.io.IOException, Exception {

		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
//		�ַ���Ϣ
		for(int i = 0 ; i < 5; i++){
			String message = "Hello World! " + i;
			channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
			System.out.println(" [x] Sent '" + message + "'");
		}
		channel.close();
		connection.close();
	}
 
Example #3
Source File: Events.java    From rabbitmqexample with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {


        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Down Stream server ip (localhost):");
        String server_ip = br.readLine();
        if (server_ip.equalsIgnoreCase("")) {
            server_ip = "localhost";
        }

        ConnectionFactory factory_down = new ConnectionFactory();
        factory_down.setHost(server_ip);
        factory_down.setUsername("test");
        factory_down.setPassword("test");
        factory_down.setVirtualHost("poc");
        Connection connection_down = factory_down.newConnection();
        System.out.println("Connected to Down Stream node: " + server_ip);
        final Channel channel_down = connection_down.createChannel();
        final String exchange = "service";
        channel_down.exchangeDeclare(exchange, "topic", true);
        channel_down.basicPublish(exchange, "r1.gis", MessageProperties.PERSISTENT_BASIC, "better".getBytes());

    }
 
Example #4
Source File: BasicPropertiesHelper.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
public static AMQP.BasicProperties copy(AMQP.BasicProperties props) {
    AMQP.BasicProperties source = props;
    if (source == null) {
        source = MessageProperties.MINIMAL_BASIC;
    }

    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
    builder.contentType(source.getContentType());
    builder.contentEncoding(source.getContentEncoding());
    builder.headers(source.getHeaders());
    builder.deliveryMode(source.getDeliveryMode());
    builder.priority(source.getPriority());
    builder.correlationId(source.getCorrelationId());
    builder.replyTo(source.getReplyTo());
    builder.expiration(source.getExpiration());
    builder.messageId(source.getMessageId());
    builder.timestamp(source.getTimestamp());
    builder.type(source.getType());
    builder.userId(source.getUserId());
    builder.appId(source.getAppId());
    builder.clusterId(source.getClusterId());
    return builder.build();
}
 
Example #5
Source File: Sender.java    From neo4j-mazerunner with Apache License 2.0 6 votes vote down vote up
public static void sendMessage(String message)
        throws java.io.IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(ConfigurationLoader.getInstance().getRabbitmqNodename());
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

    channel.basicPublish( "", TASK_QUEUE_NAME,
            MessageProperties.PERSISTENT_TEXT_PLAIN,
            message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();
}
 
Example #6
Source File: Worker.java    From neo4j-mazerunner with Apache License 2.0 6 votes vote down vote up
public static void sendMessage(String message)
        throws java.io.IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(ConfigurationLoader.getInstance().getRabbitmqNodename());
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

    channel.basicPublish( "", TASK_QUEUE_NAME,
            MessageProperties.PERSISTENT_TEXT_PLAIN,
            message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();
}
 
Example #7
Source File: ConsumerHolderTest.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
@Test
void deliverWithAckFailedAck() throws IOException {
  sut = new ConsumerHolder(eventConsumerMock, "queue", true, PREFETCH_COUNT,
      consumerChannelFactoryMock, declarationsListMock, declarerRepositoryMock);
  BasicProperties properties = MessageProperties.BASIC;
  byte[] body = "some body".getBytes();
  Envelope envelope = new Envelope(123L, false, "exchange", "routingKey");
  Delivery message = new Delivery(envelope, properties, body);
  IOException ioe = new IOException("some error");

  when(consumerChannelFactoryMock.createChannel()).thenReturn(channelMock);
  when(eventConsumerMock.consume("consumerTag", envelope, properties, body)).thenReturn(false);
  doThrow(ioe).when(channelMock).basicNack(123L, false, false);

  sut.activate();
  assertThrows(IOException.class, () -> sut.deliverWithAck("consumerTag", message));
}
 
Example #8
Source File: ConsumerHolderTest.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
@Test
void deliverWithAckSendFailed() throws IOException {
  sut = new ConsumerHolder(eventConsumerMock, "queue", true, PREFETCH_COUNT,
      consumerChannelFactoryMock, declarationsListMock, declarerRepositoryMock);
  BasicProperties properties = MessageProperties.BASIC;
  byte[] body = "some body".getBytes();
  Envelope envelope = new Envelope(123L, false, "exchange", "routingKey");
  Delivery message = new Delivery(envelope, properties, body);

  when(consumerChannelFactoryMock.createChannel()).thenReturn(channelMock);
  when(eventConsumerMock.consume("consumerTag", envelope, properties, body)).thenReturn(false);

  sut.activate();
  sut.deliverWithAck("consumerTag", message);

  verify(channelMock).basicNack(123L, false, false);
}
 
Example #9
Source File: ConsumerHolderTest.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
@Test
void deliverWithAckSuccess() throws IOException {
  sut = new ConsumerHolder(eventConsumerMock, "queue", true, PREFETCH_COUNT,
      consumerChannelFactoryMock, declarationsListMock, declarerRepositoryMock);
  BasicProperties properties = MessageProperties.BASIC;
  byte[] body = "some body".getBytes();
  Envelope envelope = new Envelope(123L, false, "exchange", "routingKey");
  Delivery message = new Delivery(envelope, properties, body);

  when(consumerChannelFactoryMock.createChannel()).thenReturn(channelMock);
  when(eventConsumerMock.consume("consumerTag", envelope, properties, body)).thenReturn(true);

  sut.activate();
  sut.deliverWithAck("consumerTag", message);

  verify(channelMock).basicAck(123L, false);
}
 
Example #10
Source File: ConsumeAMQPTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void validateSuccessfullConsumeAndTransferToSuccess() throws Exception {
    final Map<String, List<String>> routingMap = Collections.singletonMap("key1", Arrays.asList("queue1", "queue2"));
    final Map<String, String> exchangeToRoutingKeymap = Collections.singletonMap("myExchange", "key1");

    final Connection connection = new TestConnection(exchangeToRoutingKeymap, routingMap);

    try (AMQPPublisher sender = new AMQPPublisher(connection, mock(ComponentLog.class))) {
        sender.publish("hello".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange");

        ConsumeAMQP proc = new LocalConsumeAMQP(connection);
        TestRunner runner = TestRunners.newTestRunner(proc);
        runner.setProperty(ConsumeAMQP.HOST, "injvm");
        runner.setProperty(ConsumeAMQP.QUEUE, "queue1");

        runner.run();
        final MockFlowFile successFF = runner.getFlowFilesForRelationship(PublishAMQP.REL_SUCCESS).get(0);
        assertNotNull(successFF);
    }
}
 
Example #11
Source File: RabbitMqIO.java    From beam with Apache License 2.0 6 votes vote down vote up
@ProcessElement
public void processElement(ProcessContext c) throws IOException {
  RabbitMqMessage message = c.element();
  Channel channel = connectionHandler.getChannel();

  if (spec.exchange() != null) {
    channel.basicPublish(
        spec.exchange(),
        message.getRoutingKey(),
        message.createProperties(),
        message.getBody());
  }
  if (spec.queue() != null) {
    channel.basicPublish(
        "", spec.queue(), MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBody());
  }
}
 
Example #12
Source File: RabbitQueueFactory.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Queue<byte[]> sendInternal(byte[] message) throws IOException {
    BlockingQueue<Boolean> semaphore = new ArrayBlockingQueue<>(1);
    long seqNo = channel.getNextPublishSeqNo();
    unconfirmedSet.put(seqNo, semaphore);
    channel.basicPublish(DEFAULT_EXCHANGE, this.queueName, MessageProperties.PERSISTENT_BASIC, message);
    // wait for confirmation
    try {
        Boolean delivered = semaphore.poll(10, TimeUnit.SECONDS);
        if (delivered == null) throw new IOException("message sending timeout");
        if (delivered) return this;
        throw new IOException(GridBroker.TARGET_LIMIT_MESSAGE);
    } catch (InterruptedException x) {
        unconfirmedSet.remove(seqNo); // prevent a memory leak
        throw new IOException("message sending interrupted");
    }
}
 
Example #13
Source File: ClientSend1.java    From java-study with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args)
    throws java.io.IOException, TimeoutException, KeyManagementException, NoSuchAlgorithmException, URISyntaxException{
        ConnectionFactory factory=new ConnectionFactory(); //创建连接工厂
//        factory.setHost("localhost");
//        factory.setVirtualHost("my_mq");
//        factory.setUsername("zhxia");
//        factory.setPassword("123456");
        factory.setUri("amqp://guest:[email protected]:5672");//获取url
        Connection connection=factory.newConnection(); //创建连接
        Channel channel=connection.createChannel();//创建信道
        channel.queueDeclare(queue_name, durable, false, false, null); //声明消息队列,且为可持久化的
        String message="Hello world"+Math.random();
        //将队列设置为持久化之后,还需要将消息也设为可持久化的,MessageProperties.PERSISTENT_TEXT_PLAIN
        channel.basicPublish("", queue_name, MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes());
        System.out.println("Send message:"+message);
        channel.close();
        connection.close();
    }
 
Example #14
Source File: ConsumeAMQPTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void validateSuccessfullConsumeAndTransferToSuccess() throws Exception {
    Map<String, List<String>> routingMap = new HashMap<>();
    routingMap.put("key1", Arrays.asList("queue1", "queue2"));
    Map<String, String> exchangeToRoutingKeymap = new HashMap<>();
    exchangeToRoutingKeymap.put("myExchange", "key1");

    Connection connection = new TestConnection(exchangeToRoutingKeymap, routingMap);

    try (AMQPPublisher sender = new AMQPPublisher(connection, mock(ComponentLog.class))) {
        sender.publish("hello".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange");

        ConsumeAMQP pubProc = new LocalConsumeAMQP(connection);
        TestRunner runner = TestRunners.newTestRunner(pubProc);
        runner.setProperty(ConsumeAMQP.HOST, "injvm");
        runner.setProperty(ConsumeAMQP.QUEUE, "queue1");

        runner.run();
        Thread.sleep(200);
        final MockFlowFile successFF = runner.getFlowFilesForRelationship(PublishAMQP.REL_SUCCESS).get(0);
        assertNotNull(successFF);
    }

}
 
Example #15
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void mandatory_publish_with_multiple_listeners() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            TrackingCallback firstCallbackThatIsRegistedTwice = new TrackingCallback();
            TrackingCallback secondCallbackThatWillBeRemoved = new TrackingCallback();
            TrackingCallback thirdCallback = new TrackingCallback();
            channel.addReturnListener(firstCallbackThatIsRegistedTwice);
            channel.addReturnListener(firstCallbackThatIsRegistedTwice);
            channel.addReturnListener(r -> {
                throw new RuntimeException("Listener throwing exception");
            });
            ReturnListener returnListener = channel.addReturnListener(secondCallbackThatWillBeRemoved);
            channel.addReturnListener(thirdCallback);
            channel.removeReturnListener(returnListener);
            channel.basicPublish("", "unexisting", true, MessageProperties.BASIC, "msg".getBytes());
            assertThat(firstCallbackThatIsRegistedTwice.invocationCount).isEqualTo(1);
            assertThat(secondCallbackThatWillBeRemoved.invocationCount).isEqualTo(0);
            assertThat(thirdCallback.invocationCount).isEqualTo(1);
        }
    }
}
 
Example #16
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest(name = "publish to {0} should return replyCode {1}")
@CsvSource({
    "boundRoutingKey, -1",
    "unboundRoutingKey, 312",
})
void mandatory_publish_with_direct_exchange(String routingKey, int expectedReplyCode) throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            channel.exchangeDeclare("test", "direct");
            channel.queueDeclare("existingQueue", false, false, false, Collections.emptyMap()).getQueue();
            channel.queueBind("existingQueue", "test", "boundRoutingKey");
            AtomicInteger replyCodeHolder = new AtomicInteger(-1);
            ReturnCallback returnListener = r -> replyCodeHolder.set(r.getReplyCode());
            channel.addReturnListener(returnListener);
            channel.basicPublish("test", routingKey, true, MessageProperties.BASIC, "msg".getBytes());
            assertThat(replyCodeHolder.get()).isEqualTo(expectedReplyCode);
        }
    }
}
 
Example #17
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest(name = "publish to {0} should return replyCode {1}")
@CsvSource({
    "existingQueue, -1",
    "unexistingQueue, 312",
})
void mandatory_publish_with_default_exchange(String routingKey, int expectedReplyCode) throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {

            channel.queueDeclare("existingQueue", false, false, false, Collections.emptyMap()).getQueue();
            AtomicInteger replyCodeHolder = new AtomicInteger(-1);
            ReturnListener returnListener = (replyCode, replyText, exchange, routingKey1, properties, body) -> replyCodeHolder.set(replyCode);
            channel.addReturnListener(returnListener);
            channel.basicPublish("", routingKey, true, MessageProperties.BASIC, "msg".getBytes());
            assertThat(replyCodeHolder.get()).isEqualTo(expectedReplyCode);
        }
    }
}
 
Example #18
Source File: LocalMessageQueue.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
private AMQP.BasicProperties createProps(InternalMessage message) {
    if(message.getTimeout() < 0) {
        return message.isDurable() ? MessageProperties.PERSISTENT_BASIC : MessageProperties.BASIC;
    } else {
        if(message.isDurable()) {
            return new AMQP.BasicProperties.Builder().contentType("application/octet-stream").deliveryMode(2)
                    .priority(0).expiration(String.valueOf(message.getTimeout())).build();
        } else {
            return new AMQP.BasicProperties.Builder().contentType("application/octet-stream").deliveryMode(1)
                    .priority(0).expiration(String.valueOf(message.getTimeout())).build();
        }
    }
}
 
Example #19
Source File: RabbitMQMessageQueueTest.java    From dropwizard-experiment with MIT License 5 votes vote down vote up
@Test
public void shouldPublishPersistentMessageToQueue() throws IOException {
    RabbitMQMessageQueue<TestMsg> queue = new RabbitMQMessageQueue<>(channel, QUEUE_NAME, TestMsg.class, metrics);
    TestMsg message = new TestMsg("blah", 5);
    byte[] messageBytes = Jackson.newObjectMapper().writeValueAsBytes(message);

    queue.publish(message);

    verify(channel).basicPublish(Matchers.eq(""), Matchers.eq(QUEUE_NAME), Matchers.eq(MessageProperties.PERSISTENT_TEXT_PLAIN), Matchers.eq(messageBytes));
}
 
Example #20
Source File: RemoteMessageQueue.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
private AMQP.BasicProperties createProps(InternalMessage message) {
    if(message.getTimeout() < 0) {
        return message.isDurable() ? MessageProperties.PERSISTENT_BASIC : MessageProperties.BASIC;
    } else {
        if(message.isDurable()) {
            return new AMQP.BasicProperties.Builder().contentType("application/octet-stream").deliveryMode(2)
                    .priority(0).expiration(String.valueOf(message.getTimeout())).build();
        } else {
            return new AMQP.BasicProperties.Builder().contentType("application/octet-stream").deliveryMode(1)
                    .priority(0).expiration(String.valueOf(message.getTimeout())).build();
        }
    }
}
 
Example #21
Source File: RemoteMessageQueue.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
private AMQP.BasicProperties createProps(InternalMessage message) {
    if(message.getTimeout() < 0) {
        return message.isDurable() ? MessageProperties.PERSISTENT_BASIC : MessageProperties.BASIC;
    } else {
        if(message.isDurable()) {
            return new AMQP.BasicProperties.Builder().contentType("application/octet-stream").deliveryMode(2)
                    .priority(0).expiration(String.valueOf(message.getTimeout())).build();
        } else {
            return new AMQP.BasicProperties.Builder().contentType("application/octet-stream").deliveryMode(1)
                    .priority(0).expiration(String.valueOf(message.getTimeout())).build();
        }
    }
}
 
Example #22
Source File: RabbitMQMessageQueue.java    From dropwizard-experiment with MIT License 5 votes vote down vote up
@Override
public void publish(T message) {
    try {
        channel.basicPublish("", name, MessageProperties.PERSISTENT_TEXT_PLAIN, MAPPER.writeValueAsBytes(message));

        publish.mark();
        if (log.isTraceEnabled()) {
            log.trace("Published to '{}' with data '{}'.", name, MAPPER.writeValueAsString(message));
        }
    } catch (IOException e) {
        throw new MessageQueueException("Unable to publish to queue.", e);
    }
}
 
Example #23
Source File: RabbitMQEventBus.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private void publishEventToExchange(Channel channel, String exchangeName, String routingKey, String eventDescription) throws Exception {
    try {
        byte[] messageBodyBytes = eventDescription.getBytes();
        channel.basicPublish(exchangeName, routingKey, MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes);
    } catch (Exception e) {
        s_logger.error("Failed to publish event " + routingKey + " on exchange " + exchangeName + "  of message broker due to " + e.getMessage());
        throw e;
    }
}
 
Example #24
Source File: ConsumeAMQPTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testMessagesRejectedOnStop() throws TimeoutException, IOException {
    final Map<String, List<String>> routingMap = Collections.singletonMap("key1", Arrays.asList("queue1"));
    final Map<String, String> exchangeToRoutingKeymap = Collections.singletonMap("myExchange", "key1");

    final Connection connection = new TestConnection(exchangeToRoutingKeymap, routingMap);

    try (AMQPPublisher sender = new AMQPPublisher(connection, mock(ComponentLog.class))) {
        sender.publish("hello".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange");
        sender.publish("world".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange");
        sender.publish("good-bye".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange");

        LocalConsumeAMQP proc = new LocalConsumeAMQP(connection);
        TestRunner runner = TestRunners.newTestRunner(proc);
        runner.setProperty(ConsumeAMQP.HOST, "injvm");
        runner.setProperty(ConsumeAMQP.QUEUE, "queue1");
        runner.setProperty(ConsumeAMQP.BATCH_SIZE, "1");

        runner.run();
        proc.close();

        runner.assertTransferCount(PublishAMQP.REL_SUCCESS, 1);

        final MockFlowFile helloFF = runner.getFlowFilesForRelationship(PublishAMQP.REL_SUCCESS).get(0);
        helloFF.assertContentEquals("hello");


        // A single cumulative ack should be used
        assertTrue(((TestChannel) connection.createChannel()).isAck(0));

        // Messages 1 and 2 will have been delivered but on stop should be rejected. They will be rejected
        // cumulatively, though, so only delivery Tag 2 will be nack'ed explicitly
        assertTrue(((TestChannel) connection.createChannel()).isNack(2));

        // Any newly delivered messages should also be immediately nack'ed.
        proc.getAMQPWorker().getConsumer().handleDelivery("123", new Envelope(3, false, "myExchange", "key1"), new BasicProperties(), new byte[0]);
        assertTrue(((TestChannel) connection.createChannel()).isNack(3));
    }
}
 
Example #25
Source File: LocalMessageQueue.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
private AMQP.BasicProperties createProps(InternalMessage message) {
    if(message.getTimeout() < 0) {
        return message.isDurable() ? MessageProperties.PERSISTENT_BASIC : MessageProperties.BASIC;
    } else {
        if(message.isDurable()) {
            return new AMQP.BasicProperties.Builder().contentType("application/octet-stream").deliveryMode(2)
                    .priority(0).expiration(String.valueOf(message.getTimeout())).build();
        } else {
            return new AMQP.BasicProperties.Builder().contentType("application/octet-stream").deliveryMode(1)
                    .priority(0).expiration(String.valueOf(message.getTimeout())).build();
        }
    }
}
 
Example #26
Source File: ConsumeAMQPTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testBatchSizeAffectsAcks() throws TimeoutException, IOException {
    final Map<String, List<String>> routingMap = Collections.singletonMap("key1", Arrays.asList("queue1"));
    final Map<String, String> exchangeToRoutingKeymap = Collections.singletonMap("myExchange", "key1");

    final Connection connection = new TestConnection(exchangeToRoutingKeymap, routingMap);

    try (AMQPPublisher sender = new AMQPPublisher(connection, mock(ComponentLog.class))) {
        sender.publish("hello".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange");
        sender.publish("world".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange");

        ConsumeAMQP proc = new LocalConsumeAMQP(connection);
        TestRunner runner = TestRunners.newTestRunner(proc);
        runner.setProperty(ConsumeAMQP.HOST, "injvm");
        runner.setProperty(ConsumeAMQP.QUEUE, "queue1");
        runner.setProperty(ConsumeAMQP.BATCH_SIZE, "1");

        runner.run(2);

        runner.assertTransferCount(PublishAMQP.REL_SUCCESS, 2);

        final MockFlowFile helloFF = runner.getFlowFilesForRelationship(PublishAMQP.REL_SUCCESS).get(0);
        helloFF.assertContentEquals("hello");

        final MockFlowFile worldFF = runner.getFlowFilesForRelationship(PublishAMQP.REL_SUCCESS).get(1);
        worldFF.assertContentEquals("world");

        // A single cumulative ack should be used
        assertTrue(((TestChannel) connection.createChannel()).isAck(0));
        assertTrue(((TestChannel) connection.createChannel()).isAck(1));
    }
}
 
Example #27
Source File: MessageSender.java    From AuTe-Framework with Apache License 2.0 5 votes vote down vote up
private void sendRabbitMq(String queue, String text) throws IOException, TimeoutException {
  com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory();
  factory.setHost(properties.getHost());
  factory.setPort(properties.getPort());
  factory.setUsername(properties.getUsername());
  factory.setPassword(properties.getPassword());
  com.rabbitmq.client.Connection connection = factory.newConnection();
  try (Channel channel = connection.createChannel()) {
    channel.basicPublish("", queue, MessageProperties.TEXT_PLAIN, text.getBytes(StandardCharsets.UTF_8));
  }
  connection.close();
}
 
Example #28
Source File: ConsumeAMQPTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testMessageAcked() throws TimeoutException, IOException {
    final Map<String, List<String>> routingMap = Collections.singletonMap("key1", Arrays.asList("queue1"));
    final Map<String, String> exchangeToRoutingKeymap = Collections.singletonMap("myExchange", "key1");

    final Connection connection = new TestConnection(exchangeToRoutingKeymap, routingMap);

    try (AMQPPublisher sender = new AMQPPublisher(connection, mock(ComponentLog.class))) {
        sender.publish("hello".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange");
        sender.publish("world".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange");

        ConsumeAMQP proc = new LocalConsumeAMQP(connection);
        TestRunner runner = TestRunners.newTestRunner(proc);
        runner.setProperty(ConsumeAMQP.HOST, "injvm");
        runner.setProperty(ConsumeAMQP.QUEUE, "queue1");
        runner.setProperty(ConsumeAMQP.AUTO_ACKNOWLEDGE, "false");

        runner.run();

        runner.assertTransferCount(PublishAMQP.REL_SUCCESS, 2);

        final MockFlowFile helloFF = runner.getFlowFilesForRelationship(PublishAMQP.REL_SUCCESS).get(0);
        helloFF.assertContentEquals("hello");

        final MockFlowFile worldFF = runner.getFlowFilesForRelationship(PublishAMQP.REL_SUCCESS).get(1);
        worldFF.assertContentEquals("world");

        // A single cumulative ack should be used
        assertFalse(((TestChannel) connection.createChannel()).isAck(0));
        assertTrue(((TestChannel) connection.createChannel()).isAck(1));
    }
}
 
Example #29
Source File: JobProducer.java    From simpleci with MIT License 5 votes vote down vote up
public void send(JobRequestMessage requestMessage, String queueName) {
    try {
        if(!queueNamesCache.contains(queueName)) {
            channel.queueDeclare(queueName, true, false, false, null);
            queueNamesCache.add(queueName);
        }
        logger.info(String.format("Produce job to queue %s", queueName));

        String sendMessage = requestMessage.toJson().toString();
        channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, sendMessage.getBytes());
    } catch (IOException e) {
        logger.error("Error publish job message", e);
    }
}
 
Example #30
Source File: ConsumerHolderTest.java    From rabbitmq-cdi with MIT License 5 votes vote down vote up
@Test
void deliverNoAck() throws IOException {
  sut = new ConsumerHolder(eventConsumerMock, "queue", true, PREFETCH_COUNT,
      consumerChannelFactoryMock, declarationsListMock, declarerRepositoryMock);
  BasicProperties properties = MessageProperties.BASIC;
  byte[] body = "some body".getBytes();
  Envelope envelope = new Envelope(123L, false, "exchange", "routingKey");
  Delivery message = new Delivery(envelope, properties, body);

  sut.deliverNoAck("consumerTag", message);

  verify(eventConsumerMock).consume("consumerTag", envelope, properties, body);
}