com.rabbitmq.client.AMQP.BasicProperties Java Examples
The following examples show how to use
com.rabbitmq.client.AMQP.BasicProperties.
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: AgentManagementServiceImpl.java From Insights with Apache License 2.0 | 6 votes |
private void publishAgentAction(String routingKey, byte[] data, BasicProperties props) throws TimeoutException, IOException { String exchangeName = ApplicationConfigProvider.getInstance().getAgentDetails().getAgentExchange(); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(ApplicationConfigProvider.getInstance().getMessageQueue().getHost()); factory.setUsername(ApplicationConfigProvider.getInstance().getMessageQueue().getUser()); factory.setPassword(ApplicationConfigProvider.getInstance().getMessageQueue().getPassword()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, MessageConstants.EXCHANGE_TYPE, true); channel.queueDeclare(routingKey, true, false, false, null); channel.queueBind(routingKey, exchangeName, routingKey); channel.basicPublish(exchangeName, routingKey, props, data); channel.close(); connection.close(); }
Example #2
Source File: GenericPublisherTest.java From rabbitmq-cdi with MIT License | 6 votes |
@Test public void testPublish_with_FatalError() throws Exception { Builder builder = new Builder(); PublisherConfiguration<TestEvent> publisherConfiguration = new PublisherConfiguration(config, "exchange", routingKeyFunction, builder, new JsonEncoder<>(), errorHandler, declarations); ArgumentCaptor<BasicProperties> propsCaptor = ArgumentCaptor.forClass(BasicProperties.class); when(connectionRepository.getConnection(config)).thenReturn(connection); when(connection.createChannel()).thenReturn(channel); doThrow(new IOException("someError")).when(channel).basicPublish(eq("exchange"), eq("routingKey"), propsCaptor.capture(), eq("{\"id\":\"theId\",\"booleanValue\":true}".getBytes())); Throwable exception = assertThrows(PublishException.class, () -> { publisher.publish(event, publisherConfiguration); }); assertEquals("Unable to send message after 3 attempts", exception.getMessage()); assertEquals("application/json", propsCaptor.getValue().getContentType()); }
Example #3
Source File: GenericPublisherTest.java From rabbitmq-cdi with MIT License | 6 votes |
@Test public void testPublish_with_error() throws Exception { Builder builder = new Builder(); PublisherConfiguration<TestEvent> publisherConfiguration = new PublisherConfiguration(config, "exchange", routingKeyFunction, builder, new JsonEncoder<>(), errorHandler, declarations); ArgumentCaptor<BasicProperties> propsCaptor = ArgumentCaptor.forClass(BasicProperties.class); when(connectionRepository.getConnection(config)).thenReturn(connection); when(connection.createChannel()).thenReturn(channel); doThrow(new IOException("someError")).when(channel).basicPublish(eq("exchange"), eq("routingKey"), propsCaptor.capture(), eq("{\"id\":\"theId\",\"booleanValue\":true}".getBytes())); Throwable exception = assertThrows(PublishException.class, () -> { publisher.publish(event, publisherConfiguration); }); assertEquals("Unable to send message after 3 attempts", exception.getMessage()); assertEquals("application/json", propsCaptor.getValue().getContentType()); }
Example #4
Source File: ConsumeAMQP.java From localization_nifi with Apache License 2.0 | 6 votes |
/** * Will construct a {@link FlowFile} containing the body of the consumed * AMQP message (if {@link GetResponse} returned by {@link AMQPConsumer} is * not null) and AMQP properties that came with message which are added to a * {@link FlowFile} as attributes, transferring {@link FlowFile} to * 'success' {@link Relationship}. */ @Override protected void rendezvousWithAmqp(ProcessContext context, ProcessSession processSession) throws ProcessException { final GetResponse response = this.targetResource.consume(); if (response != null){ FlowFile flowFile = processSession.create(); flowFile = processSession.write(flowFile, new OutputStreamCallback() { @Override public void process(final OutputStream out) throws IOException { out.write(response.getBody()); } }); BasicProperties amqpProperties = response.getProps(); flowFile = AMQPUtils.updateFlowFileAttributesWithAmqpProperties(amqpProperties, flowFile, processSession); processSession.getProvenanceReporter().receive(flowFile, this.amqpConnection.toString() + "/" + context.getProperty(QUEUE).getValue()); processSession.transfer(flowFile, REL_SUCCESS); } else { context.yield(); } }
Example #5
Source File: AMQPPublisher.java From localization_nifi with Apache License 2.0 | 6 votes |
/** * Publishes message with provided AMQP properties (see * {@link BasicProperties}) to a pre-defined AMQP Exchange. * * @param bytes * bytes representing a message. * @param properties * instance of {@link BasicProperties} * @param exchange * the name of AMQP exchange to which messages will be published. * If not provided 'default' exchange will be used. * @param routingKey * (required) the name of the routingKey to be used by AMQP-based * system to route messages to its final destination (queue). */ void publish(byte[] bytes, BasicProperties properties, String routingKey, String exchange) { this.validateStringProperty("routingKey", routingKey); exchange = exchange == null ? "" : exchange.trim(); if (exchange.length() == 0) { processLog.info("The 'exchangeName' is not specified. Messages will be sent to default exchange"); } processLog.info("Successfully connected AMQPPublisher to " + this.connectionString + " and '" + exchange + "' exchange with '" + routingKey + "' as a routing key."); if (this.channel.isOpen()) { try { this.channel.basicPublish(exchange, routingKey, true, properties, bytes); } catch (Exception e) { throw new IllegalStateException("Failed to publish to '" + exchange + "' with '" + routingKey + "'.", e); } } else { throw new IllegalStateException("This instance of AMQPPublisher is invalid since " + "its publishingChannel is closed"); } }
Example #6
Source File: PublishAMQP.java From nifi with Apache License 2.0 | 6 votes |
/** * Extracts AMQP properties from the {@link FlowFile} attributes. Attributes * extracted from {@link FlowFile} are considered candidates for AMQP * properties if their names are prefixed with * {@link AMQPUtils#AMQP_PROP_PREFIX} (e.g., amqp$contentType=text/xml). * * Some fields require a specific format and are validated: * * {@link AMQPUtils#validateAMQPHeaderProperty} * {@link AMQPUtils#validateAMQPDeliveryModeProperty} * {@link AMQPUtils#validateAMQPPriorityProperty} * {@link AMQPUtils#validateAMQPTimestampProperty} */ private BasicProperties extractAmqpPropertiesFromFlowFile(FlowFile flowFile) { final AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder(); updateBuilderFromAttribute(flowFile, "contentType", builder::contentType); updateBuilderFromAttribute(flowFile, "contentEncoding", builder::contentEncoding); updateBuilderFromAttribute(flowFile, "deliveryMode", mode -> builder.deliveryMode(Integer.parseInt(mode))); updateBuilderFromAttribute(flowFile, "priority", pri -> builder.priority(Integer.parseInt(pri))); updateBuilderFromAttribute(flowFile, "correlationId", builder::correlationId); updateBuilderFromAttribute(flowFile, "replyTo", builder::replyTo); updateBuilderFromAttribute(flowFile, "expiration", builder::expiration); updateBuilderFromAttribute(flowFile, "messageId", builder::messageId); updateBuilderFromAttribute(flowFile, "timestamp", ts -> builder.timestamp(new Date(Long.parseLong(ts)))); updateBuilderFromAttribute(flowFile, "type", builder::type); updateBuilderFromAttribute(flowFile, "userId", builder::userId); updateBuilderFromAttribute(flowFile, "appId", builder::appId); updateBuilderFromAttribute(flowFile, "clusterId", builder::clusterId); updateBuilderFromAttribute(flowFile, "headers", headers -> builder.headers(validateAMQPHeaderProperty(headers))); return builder.build(); }
Example #7
Source File: ConsumerHolderTest.java From rabbitmq-cdi with MIT License | 6 votes |
@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 #8
Source File: MockQueue.java From rabbitmq-mock with Apache License 2.0 | 6 votes |
public boolean publish(String exchangeName, String routingKey, AMQP.BasicProperties props, byte[] body) { boolean queueLengthLimitReached = queueLengthLimitReached() || queueLengthBytesLimitReached(); if (queueLengthLimitReached && arguments.overflow() == AmqArguments.Overflow.REJECT_PUBLISH) { return true; } Message message = new Message( messageSequence.incrementAndGet(), exchangeName, routingKey, props, body, computeExpiryTime(props) ); if (message.expiryTime != -1) { LOGGER.debug(localized("Message published expiring at " + Instant.ofEpochMilli(message.expiryTime)) + ": " + message); } else { LOGGER.debug(localized("Message published" + ": " + message)); } messages.offer(message); if (queueLengthLimitReached) { deadLetterWithReason(messages.poll(), DeadLettering.ReasonType.MAX_LEN); } return true; }
Example #9
Source File: TestChannel.java From nifi with Apache License 2.0 | 6 votes |
private void discard(final String exchange, final String routingKey, boolean mandatory, final BasicProperties props, final byte[] body) { // NO ROUTE. Invoke return listener async for (final ReturnListener listener : returnListeners) { this.executorService.execute(new Runnable() { @Override public void run() { try { listener.handleReturn(-9, "Rejecting", exchange, routingKey, props, body); } catch (Exception e) { throw new IllegalStateException("Failed to send return message", e); } } }); } }
Example #10
Source File: ConsumerHolderTest.java From rabbitmq-cdi with MIT License | 6 votes |
@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 #11
Source File: ConsumerHolderTest.java From rabbitmq-cdi with MIT License | 6 votes |
@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 #12
Source File: MessageProperties.java From zstack with Apache License 2.0 | 6 votes |
public static MessageProperties valueOf(BasicProperties bp) { MessageProperties mp = new MessageProperties(); mp.setAppId(bp.getAppId()); mp.setClusterId(bp.getClusterId()); mp.setContentEncoding(bp.getContentEncoding()); mp.setContentType(bp.getContentType()); mp.setCorrelationId(bp.getCorrelationId()); mp.setDeliveryMode(bp.getDeliveryMode()); mp.setExpiration(bp.getExpiration()); mp.setHeaders(bp.getHeaders()); mp.setMessageId(bp.getMessageId()); mp.setPriority(bp.getPriority()); mp.setReplyTo(bp.getReplyTo()); mp.setTimestamp(bp.getTimestamp()); mp.setType(bp.getType()); mp.setUserId(bp.getUserId()); return mp; }
Example #13
Source File: AmqpForwardAttributeTest.java From james-project with Apache License 2.0 | 6 votes |
@Test public void serviceShouldPublishAttributeContentWhenAttributeInMailAndIsAMap() throws Exception { mailet.init(mailetConfig); Channel channel = mock(Channel.class); Connection connection = mock(Connection.class); when(connection.createChannel()).thenReturn(channel); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); when(connectionFactory.newConnection()).thenReturn(connection); mailet.setConnectionFactory(connectionFactory); Mail mail = mock(Mail.class); when(mail.getAttribute(MAIL_ATTRIBUTE)).thenReturn(ATTRIBUTE_CONTENT); BasicProperties expectedProperties = new AMQP.BasicProperties(); mailet.service(mail); ArgumentCaptor<BasicProperties> basicPropertiesCaptor = ArgumentCaptor.forClass(BasicProperties.class); verify(channel).basicPublish(eq(EXCHANGE_NAME), eq(ROUTING_KEY), basicPropertiesCaptor.capture(), eq(ATTACHMENT_CONTENT)); assertThat(basicPropertiesCaptor.getValue()).isEqualToComparingFieldByField(expectedProperties); }
Example #14
Source File: GenericPublisherTest.java From rabbitmq-cdi with MIT License | 6 votes |
@Test public void testPublish_with_custom_MessageConverter() throws Exception { Builder builder = new Builder(); PublisherConfiguration<TestEvent> publisherConfiguration = new PublisherConfiguration(config, "exchange", routingKeyFunction, builder, new CustomEncoder(), errorHandler, declarations); ArgumentCaptor<BasicProperties> propsCaptor = ArgumentCaptor.forClass(BasicProperties.class); when(connectionRepository.getConnection(config)).thenReturn(connection); when(connection.createChannel()).thenReturn(channel); publisher.publish(event, publisherConfiguration); verify(channel).basicPublish(eq("exchange"), eq("routingKey"), propsCaptor.capture(), eq("Id: theId, BooleanValue: true".getBytes())); assertEquals("text/plain", propsCaptor.getValue().getContentType()); }
Example #15
Source File: AmqpForwardAttributeTest.java From james-project with Apache License 2.0 | 6 votes |
@Test public void serviceShouldPublishAttributeContentWhenAttributeInMailAndIsAList() throws Exception { mailet.init(mailetConfig); Channel channel = mock(Channel.class); Connection connection = mock(Connection.class); when(connection.createChannel()).thenReturn(channel); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); when(connectionFactory.newConnection()).thenReturn(connection); mailet.setConnectionFactory(connectionFactory); Mail mail = mock(Mail.class); when(mail.getAttribute(MAIL_ATTRIBUTE)).thenReturn(Optional.of(new Attribute(MAIL_ATTRIBUTE, AttributeValue.of(ImmutableList.of(AttributeValue.ofSerializable(ATTACHMENT_CONTENT)))))); BasicProperties expectedProperties = new AMQP.BasicProperties(); mailet.service(mail); ArgumentCaptor<BasicProperties> basicPropertiesCaptor = ArgumentCaptor.forClass(BasicProperties.class); verify(channel).basicPublish(eq(EXCHANGE_NAME), eq(ROUTING_KEY), basicPropertiesCaptor.capture(), eq(ATTACHMENT_CONTENT)); assertThat(basicPropertiesCaptor.getValue()).isEqualToComparingFieldByField(expectedProperties); }
Example #16
Source File: TestChannel.java From localization_nifi with Apache License 2.0 | 6 votes |
private void discard(final String exchange, final String routingKey, boolean mandatory, final BasicProperties props, final byte[] body) { // NO ROUTE. Invoke return listener async for (final ReturnListener listener : returnListeners) { this.executorService.execute(new Runnable() { @Override public void run() { try { listener.handleReturn(-9, "Rejecting", exchange, routingKey, props, body); } catch (Exception e) { throw new IllegalStateException("Failed to send return message", e); } } }); } }
Example #17
Source File: AMQPPublisherTest.java From localization_nifi with Apache License 2.0 | 6 votes |
@Test public void validateSuccessfullPublishingAndUndeliverableRoutingKey() 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); ReturnListener retListener = mock(ReturnListener.class); connection.createChannel().addReturnListener(retListener); try (AMQPPublisher sender = new AMQPPublisher(connection, new MockComponentLog("foo", ""))) { sender.publish("hello".getBytes(), null, "key1", "myExchange"); Thread.sleep(1000); } Thread.sleep(200); verify(retListener, atMost(1)).handleReturn(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(BasicProperties.class), (byte[]) Mockito.any()); connection.close(); }
Example #18
Source File: AMQPUtilsTest.java From localization_nifi with Apache License 2.0 | 6 votes |
@Test public void validateUpdateFlowFileAttributesWithAmqpProperties() { PublishAMQP processor = new PublishAMQP(); ProcessSession processSession = new MockProcessSession(new SharedSessionState(processor, new AtomicLong()), processor); FlowFile sourceFlowFile = processSession.create(); BasicProperties amqpProperties = new AMQP.BasicProperties.Builder() .contentType("text/plain").deliveryMode(2) .priority(1).userId("joe") .build(); FlowFile f2 = AMQPUtils.updateFlowFileAttributesWithAmqpProperties(amqpProperties, sourceFlowFile, processSession); assertEquals("text/plain", f2.getAttributes().get(AMQPUtils.AMQP_PROP_PREFIX + "contentType")); assertEquals("joe", f2.getAttributes().get(AMQPUtils.AMQP_PROP_PREFIX + "userId")); assertEquals("2", f2.getAttributes().get(AMQPUtils.AMQP_PROP_PREFIX + "deliveryMode")); }
Example #19
Source File: ProducerExchangeConsumer_Fanout.java From util4j with Apache License 2.0 | 6 votes |
public void producer() throws Exception{ //1、获取连接 Connection connection = RabbitMqConnectionFactoy.getConnection(); //2、声明信道 Channel channel = connection.createChannel(); //3、声明(创建)交换机 channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT); Thread.sleep(3000); //4、定义消息内容(发布多条消息) for(int i = 0 ; i < 10 ; i++){ String message = "hello rabbitmq "+i; //定义消息头 Map<String,Object> header=new HashMap<>(); header.put("i",i); BasicProperties bp=new BasicProperties.Builder().headers(header).build(); //5、发布消息 channel.basicPublish(EXCHANGE_NAME,"",bp,message.getBytes()); System.out.println("[x] Sent'"+message+"'"); //模拟发送消息延时,便于演示多个消费者竞争接受消息 // Thread.sleep(i*10); } //6、关闭通道 channel.close(); //7、关闭连接 connection.close(); }
Example #20
Source File: ProducerExchangeConsumer_Fanout.java From util4j with Apache License 2.0 | 6 votes |
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 #21
Source File: EventConsumerTest.java From rabbitmq-cdi with MIT License | 6 votes |
@SuppressWarnings("boxing") @Test public void testHandleDelivery() throws Exception { TestEvent event = new TestEvent(); byte[] body = "the message".getBytes(); Envelope envelope = new Envelope(123L, false, null, null); BasicProperties properties = new BasicProperties(); when(decoder.willDecode(null)).thenReturn(true); when(decoder.decode(body)).thenReturn(event); when(eventSink.select(TestEvent.class)).thenReturn(testEventSink); assertTrue(consumer.consume("consumerTag", envelope, properties, body)); verify(testEventSink).fire(event); }
Example #22
Source File: RpcTest.java From util4j with Apache License 2.0 | 6 votes |
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 #23
Source File: AmqpForwardAttributeTest.java From james-project with Apache License 2.0 | 6 votes |
@Test public void serviceShouldPublishAttributeContentWhenAttributeInMailAndIsAString() throws Exception { mailet.init(mailetConfig); Channel channel = mock(Channel.class); Connection connection = mock(Connection.class); when(connection.createChannel()).thenReturn(channel); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); when(connectionFactory.newConnection()).thenReturn(connection); mailet.setConnectionFactory(connectionFactory); Mail mail = mock(Mail.class); String content = "Attachment content"; when(mail.getAttribute(MAIL_ATTRIBUTE)).thenReturn(Optional.of(new Attribute(MAIL_ATTRIBUTE, AttributeValue.of(content)))); BasicProperties expectedProperties = new AMQP.BasicProperties(); mailet.service(mail); ArgumentCaptor<BasicProperties> basicPropertiesCaptor = ArgumentCaptor.forClass(BasicProperties.class); verify(channel).basicPublish(eq(EXCHANGE_NAME), eq(ROUTING_KEY), basicPropertiesCaptor.capture(), eq(content.getBytes(StandardCharsets.UTF_8))); assertThat(basicPropertiesCaptor.getValue()).isEqualToComparingFieldByField(expectedProperties); }
Example #24
Source File: ProducerConsumer.java From util4j with Apache License 2.0 | 6 votes |
public void producer() throws Exception{ //1、获取连接 Connection connection = RabbitMqConnectionFactoy.getConnection(); //2、声明信道 Channel channel = connection.createChannel(); //3、声明(创建)队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); //4、定义消息内容(发布多条消息) for(int i = 0 ; i < 10 ; i++){ String message = "hello rabbitmq "+i; //定义消息头 Map<String,Object> header=new HashMap<>(); header.put("i",i); BasicProperties bp=new BasicProperties.Builder().headers(header).build(); //5、发布消息 channel.basicPublish("",QUEUE_NAME,bp,message.getBytes()); System.out.println("[x] Sent'"+message+"'"); //模拟发送消息延时,便于演示多个消费者竞争接受消息 // Thread.sleep(i*10); } //6、关闭通道 channel.close(); //7、关闭连接 connection.close(); }
Example #25
Source File: RabbitMqMessage.java From beam with Apache License 2.0 | 6 votes |
/** * Make delivery serializable by cloning all non-serializable values into serializable ones. If it * is not possible, initial delivery is returned and error message is logged * * @param processed * @return */ private static GetResponse serializableDeliveryOf(GetResponse processed) { // All content of envelope is serializable, so no problem there Envelope envelope = processed.getEnvelope(); // in basicproperties, there may be LongString, which are *not* serializable BasicProperties properties = processed.getProps(); BasicProperties nextProperties = new BasicProperties.Builder() .appId(properties.getAppId()) .clusterId(properties.getClusterId()) .contentEncoding(properties.getContentEncoding()) .contentType(properties.getContentType()) .correlationId(properties.getCorrelationId()) .deliveryMode(properties.getDeliveryMode()) .expiration(properties.getExpiration()) .headers(serializableHeaders(properties.getHeaders())) .messageId(properties.getMessageId()) .priority(properties.getPriority()) .replyTo(properties.getReplyTo()) .timestamp(properties.getTimestamp()) .type(properties.getType()) .userId(properties.getUserId()) .build(); return new GetResponse( envelope, nextProperties, processed.getBody(), processed.getMessageCount()); }
Example #26
Source File: TestClient.java From rabbitmq-cdi with MIT License | 6 votes |
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 #27
Source File: ProducerExchangeConsumer_Topic.java From util4j with Apache License 2.0 | 6 votes |
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 #28
Source File: ProducerExchangeConsumer_Topic.java From util4j with Apache License 2.0 | 6 votes |
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 #29
Source File: AMQPPublisher.java From nifi with Apache License 2.0 | 6 votes |
/** * Publishes message with provided AMQP properties (see * {@link BasicProperties}) to a pre-defined AMQP Exchange. * * @param bytes bytes representing a message. * @param properties instance of {@link BasicProperties} * @param exchange the name of AMQP exchange to which messages will be published. * If not provided 'default' exchange will be used. * @param routingKey (required) the name of the routingKey to be used by AMQP-based * system to route messages to its final destination (queue). */ void publish(byte[] bytes, BasicProperties properties, String routingKey, String exchange) { this.validateStringProperty("routingKey", routingKey); exchange = exchange == null ? "" : exchange.trim(); if (exchange.length() == 0) { processLog.info("The 'exchangeName' is not specified. Messages will be sent to default exchange"); } processLog.info("Successfully connected AMQPPublisher to " + this.connectionString + " and '" + exchange + "' exchange with '" + routingKey + "' as a routing key."); final Channel channel = getChannel(); if (channel.isOpen()) { try { channel.basicPublish(exchange, routingKey, true, properties, bytes); } catch (Exception e) { throw new IllegalStateException("Failed to publish to Exchange '" + exchange + "' with Routing Key '" + routingKey + "'.", e); } } else { throw new IllegalStateException("This instance of AMQPPublisher is invalid since its publishingChannel is closed"); } }
Example #30
Source File: RoboconfConsumer.java From roboconf-platform with Apache License 2.0 | 6 votes |
@Override public void handleDelivery( String consumerTag, Envelope envelope, BasicProperties properties, byte[] body ) throws IOException { try { Message message = SerializationUtils.deserializeObject( body ); this.logger.finer( this.sourceName + " received a message " + message.getClass().getSimpleName() + " on routing key '" + envelope.getRoutingKey() + "'."); this.messageQueue.add( message ); } catch( ClassNotFoundException | IOException e ) { this.logger.severe( this.sourceName + ": a message could not be deserialized. => " + e.getClass().getSimpleName()); Utils.logException( this.logger, e ); this.messageQueue.errorWhileReceivingMessage(); } }