Example usage for org.springframework.amqp.core Message Message

List of usage examples for org.springframework.amqp.core Message Message

Introduction

In this page you can find the example usage for org.springframework.amqp.core Message Message.

Prototype

public Message(byte[] body, MessageProperties messageProperties) 

Source Link

Usage

From source file:com.xoom.rabbit.test.Main.java

public static void main(String[] args) throws InterruptedException {
    if (args.length != 9) {
        System.out.println(/*w ww  .  j a v a 2  s  . c om*/
                "usage: java -jar target/rabbit-tester-0.1-SNAPSHOT-standalone.jar [consumer_threads] [number_of_messages] [amqp_host] [amqp_port] [produce] [consume] [message size in bytes] [username] [password]");
        return;
    }
    final long startTime = System.currentTimeMillis();
    int consumerThreads = Integer.parseInt(args[0]);
    final int messages = Integer.parseInt(args[1]);
    String host = args[2];
    int port = Integer.parseInt(args[3]);
    boolean produce = Boolean.parseBoolean(args[4]);
    boolean consume = Boolean.parseBoolean(args[5]);
    final int messageSize = Integer.parseInt(args[6]);
    String username = args[7];
    String password = args[8];

    if (produce) {
        System.out.println("Sending " + messages + " messages to " + host + ":" + port);
    }
    if (consume) {
        System.out.println("Consuming " + messages + " messages from " + host + ":" + port);
    }
    if (!produce && !consume) {
        System.out.println("Not producing or consuming any messages.");
    }

    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    connectionFactory.setChannelCacheSize(consumerThreads + 1);

    RabbitAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

    DirectExchange exchange = new DirectExchange(EXCHANGE_NAME, true, false);
    Queue queue = new Queue(QUEUE_NAME);
    amqpAdmin.declareExchange(exchange);
    amqpAdmin.declareQueue(queue);
    amqpAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY));

    final AmqpTemplate amqpTemplate = new RabbitTemplate(connectionFactory);

    final CountDownLatch producerLatch = new CountDownLatch(messages);
    final CountDownLatch consumerLatch = new CountDownLatch(messages);

    SimpleMessageListenerContainer listenerContainer = null;

    if (consume) {
        listenerContainer = new SimpleMessageListenerContainer();
        listenerContainer.setConnectionFactory(connectionFactory);
        listenerContainer.setQueueNames(QUEUE_NAME);
        listenerContainer.setConcurrentConsumers(consumerThreads);
        listenerContainer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                if (consumerLatch.getCount() == 1) {
                    System.out.println("Finished consuming " + messages + " messages in "
                            + (System.currentTimeMillis() - startTime) + "ms");
                }
                consumerLatch.countDown();
            }
        });
        listenerContainer.start();
    }

    if (produce) {
        while (producerLatch.getCount() > 0) {
            try {
                byte[] message = new byte[messageSize];
                RND.nextBytes(message);
                amqpTemplate.send(EXCHANGE_NAME, ROUTING_KEY, new Message(message, new MessageProperties()));
                producerLatch.countDown();
            } catch (Exception e) {
                System.out.println("Failed to send message " + (messages - producerLatch.getCount())
                        + " will retry forever.");
            }
        }
    }

    if (consume) {
        consumerLatch.await();
        listenerContainer.shutdown();
    }

    connectionFactory.destroy();
}

From source file:amqp.spring.camel.component.SpringAMQPHeaderTest.java

@Test
public void fromBasicProperties() throws Exception {
    MessageProperties properties = new MessageProperties();
    properties.setHeader("NotSecret", "Popcorn");
    org.springframework.amqp.core.Message message = new Message(new byte[] {}, properties);
    message.getMessageProperties().setPriority(1);
    message.getMessageProperties().setReplyTo("BuzzSaw");

    SpringAMQPMessage camelMessage = SpringAMQPHeader.setBasicPropertiesToHeaders(new SpringAMQPMessage(),
            message);//from w  w w. ja v a 2s. co m
    Assert.assertNull(camelMessage.getHeader("NotSecret"));
    Assert.assertEquals(1, camelMessage.getHeader(SpringAMQPHeader.PRIORITY));
    Assert.assertEquals("BuzzSaw", camelMessage.getHeader(SpringAMQPHeader.REPLY_TO));
}

From source file:lpp.rabbitmq.spring.MessageConverter.java

protected Message createMessage(Object arg0, MessageProperties arg1) {
    return new Message(SerializationUtils.serialize(arg0), arg1);
}

From source file:com.anton.dev.tqrbs2.test.TestSender.java

public void sendMessage() {
    String msg = "mensaje de test en cola";
    final Message message = new Message(msg.getBytes(), new MessageProperties());
    LOGGER.info("Enviando: " + msg);
    // template.send("myExchange", "userMesssage", message);        
    template.convertAndSend("myExchange", "userMesssage", msg);
}

From source file:com.jbrisbin.vpc.jobsched.exe.ExeMessageConverter.java

public Message toMessage(Object object, MessageProperties props) throws MessageConversionException {
    if (object instanceof ExeMessage) {
        ExeMessage msg = (ExeMessage) object;
        return new Message(msg.getOutputBytes(), props);
    } else {/*w w  w  .j ava 2  s.  c o  m*/
        throw new MessageConversionException(
                "Cannot convert object " + String.valueOf(object) + " using " + getClass().toString());
    }
}

From source file:com.jbrisbin.vpc.jobsched.sql.SqlMessageConverter.java

public Message toMessage(Object object, MessageProperties props) throws MessageConversionException {
    if (object instanceof SqlMessage) {
        SqlMessage msg = (SqlMessage) object;
        props.setCorrelationId(msg.getId().getBytes());
        byte[] bytes;
        try {/* www.  java  2 s . c o m*/
            bytes = unmapObject(msg.getResults());
        } catch (IOException e) {
            throw new MessageConversionException(e.getMessage(), e);
        }
        props.setContentType("application/json");

        return new Message(bytes, props);
    } else {
        throw new MessageConversionException(
                "Cannot convert object " + String.valueOf(object) + " using " + getClass().toString());
    }
}

From source file:amqp.spring.camel.component.SpringAMQPHeaderTest.java

@Test
public void toBasicProperties() throws Exception {
    SpringAMQPMessage camelMessage = new SpringAMQPMessage();
    camelMessage.setHeader("Secret", "My Secret");
    camelMessage.setHeader(SpringAMQPHeader.PRIORITY, 1);
    camelMessage.setHeader(SpringAMQPHeader.REPLY_TO, "BuzzSaw");

    Exchange exchange = new DefaultExchange(new DefaultCamelContext());
    exchange.setIn(camelMessage);/*from  ww w . j  a v a  2 s .c  om*/

    Message message = new Message(new byte[] {}, new MessageProperties());
    message = SpringAMQPHeader.setBasicPropertiesFromHeaders(message, camelMessage.getHeaders());
    Assert.assertNull(message.getMessageProperties().getHeaders().get("Secret"));
    Assert.assertEquals(Integer.valueOf(1), message.getMessageProperties().getPriority());
    Assert.assertEquals("BuzzSaw", message.getMessageProperties().getReplyTo());
}

From source file:amqp.spring.converter.StringConverter.java

@Override
protected Message createMessage(Object object, MessageProperties messageProperties) {
    try {/*from ww  w  .j a v a 2s  .com*/
        byte[] body = null;
        if (object != null) {
            body = object.toString().getBytes(this.encoding);
        }

        String msgContentType = this.contentType == null ? DEFAULT_CONTENT_TYPE : this.contentType;
        messageProperties.setContentType(msgContentType);
        messageProperties.setContentEncoding(this.encoding);
        messageProperties.setContentLength(body != null ? body.length : 0);
        return new Message(body, messageProperties);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Cannot encode strings as {}", this.encoding, ex);
        throw new MessageConversionException("Cannot encode strings as " + this.encoding, ex);
    }
}

From source file:com.dc.gameserver.extComponents.SpringRabbitmq.FastJsonMessageConverter.java

protected Message createMessage(Object objectToConvert, MessageProperties messageProperties)
        throws MessageConversionException {
    byte[] bytes = null;
    try {//from  w w w  .  j a  v a2 s .com
        String jsonString = JSON.toJSONString(objectToConvert);
        bytes = jsonString.getBytes(this.defaultCharset);
    } catch (UnsupportedEncodingException e) {
        throw new MessageConversionException("Failed to convert Message content", e);
    }
    messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
    messageProperties.setContentEncoding(this.defaultCharset);
    messageProperties.setContentLength(bytes.length);
    return new Message(bytes, messageProperties);

}

From source file:org.kairosdb.plugin.rabbitmq.consumers.SpringJSONConsumer.java

/**
 * Decodes consumed messaged as a Sprint Message Object and treat its body as a usual
 * JSON message.//ww w  .  ja  v a2s . c  om
 * 
 * @param msg the message
 */
@Override
public Boolean consume(byte[] msg) {
    // Decodes message first
    Message message = new Message(msg, null);
    return super.consume(message.getBody());
}