Example usage for javax.jms DeliveryMode NON_PERSISTENT

List of usage examples for javax.jms DeliveryMode NON_PERSISTENT

Introduction

In this page you can find the example usage for javax.jms DeliveryMode NON_PERSISTENT.

Prototype

int NON_PERSISTENT

To view the source code for javax.jms DeliveryMode NON_PERSISTENT.

Click Source Link

Document

This is the lowest-overhead delivery mode because it does not require that the message be logged to stable storage.

Usage

From source file:de.klemp.middleware.controller.Controller.java

/**
 * This method creates a connection to the message broker Active MQ and
 * sends the message to the given topic. The method is used by all methods
 * of the second component./*www .  j av  a  2 s  .  c o  m*/
 * 
 * @param message
 *            send to the output device
 * @param topic
 *            of the message broker
 */
public static void sendMessage(String message, String topic) {
    String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

    // Create a Connection
    Connection connection;
    try {
        connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // Create the destination (Topic or Queue)
        Destination destination = session.createTopic(topic);
        // Create a MessageProducer from the Session to the Topic or Queue
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        // Create a messages
        TextMessage message1 = session.createTextMessage(message);
        // Tell the producer to send the message
        producer.send(message1);
        session.close();
        connection.close();
    } catch (JMSException e) {
        logger.error("Message could not be sended to activemq", e);
    }

}

From source file:org.mot.common.mq.ActiveMQFactory.java

/**
 * Create a new message producer onto a particular destination
 * /* w ww  . j  a  v  a2s . c om*/
 * @param destination - destination queue/topic object
 * @return the message producer object
 */
public MessageProducer createMessageProducer(String channel, long ttl, boolean persistent) {
    Destination destination = createDestination(channel);
    MessageProducer msg = null;

    try {
        msg = session.createProducer(destination);

        msg.setTimeToLive(ttl);

        if (persistent) {
            msg.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            msg.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }

    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return msg;
}

From source file:org.mule.transport.jms.Jms11Support.java

public void send(MessageProducer producer, Message message, Destination dest, boolean persistent, int priority,
        long ttl, boolean topic, ImmutableEndpoint endpoint) throws JMSException {
    producer.send(dest, message, (persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT), priority,
            ttl);/* w  ww  .j ava  2s. c  o m*/
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testQueueMessageSizePersistentAndNonPersistent() throws Exception {

    AtomicLong publishedNonPersistentMessageSize = new AtomicLong();
    AtomicLong publishedMessageSize = new AtomicLong();

    publishTestQueueMessages(100, DeliveryMode.PERSISTENT, publishedMessageSize);
    publishTestQueueMessages(100, DeliveryMode.NON_PERSISTENT, publishedNonPersistentMessageSize);
    verifyPendingStats(defaultQueueName, 200,
            publishedMessageSize.get() + publishedNonPersistentMessageSize.get());
    verifyPendingDurableStats(defaultQueueName, 100, publishedMessageSize.get());
}

From source file:org.apache.activemq.network.BrokerNetworkWithStuckMessagesTest.java

@Test(timeout = 120000)
public void testBrokerNetworkWithStuckMessages() throws Exception {

    int sendNumMessages = 10;
    int receiveNumMessages = 5;

    // Create a producer
    StubConnection connection1 = createConnection();
    ConnectionInfo connectionInfo1 = createConnectionInfo();
    SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1);
    ProducerInfo producerInfo = createProducerInfo(sessionInfo1);
    connection1.send(connectionInfo1);//from www. jav a 2 s  . co m
    connection1.send(sessionInfo1);
    connection1.send(producerInfo);

    // Create a destination on the local broker
    ActiveMQDestination destinationInfo1 = null;

    // Send a 10 messages to the local broker
    for (int i = 0; i < sendNumMessages; ++i) {
        destinationInfo1 = createDestinationInfo(connection1, connectionInfo1, ActiveMQDestination.QUEUE_TYPE);
        connection1.request(createMessage(producerInfo, destinationInfo1, DeliveryMode.NON_PERSISTENT));
    }

    // Ensure that there are 10 messages on the local broker
    Object[] messages = browseQueueWithJmx(localBroker);
    assertEquals(sendNumMessages, messages.length);

    // Create a synchronous consumer on the remote broker
    StubConnection connection2 = createRemoteConnection();
    ConnectionInfo connectionInfo2 = createConnectionInfo();
    SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2);
    connection2.send(connectionInfo2);
    connection2.send(sessionInfo2);
    ActiveMQDestination destinationInfo2 = createDestinationInfo(connection2, connectionInfo2,
            ActiveMQDestination.QUEUE_TYPE);
    final ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destinationInfo2);
    connection2.send(consumerInfo2);

    // Consume 5 of the messages from the remote broker and ack them.
    for (int i = 0; i < receiveNumMessages; ++i) {
        Message message1 = receiveMessage(connection2, 20000);
        assertNotNull(message1);
        LOG.info("on remote, got: " + message1.getMessageId());
        connection2.send(createAck(consumerInfo2, message1, 1, MessageAck.INDIVIDUAL_ACK_TYPE));
        assertTrue("JMSActiveMQBrokerPath property present and correct",
                ((ActiveMQMessage) message1).getStringProperty(ActiveMQMessage.BROKER_PATH_PROPERTY)
                        .contains(localBroker.getBroker().getBrokerId().toString()));
    }

    // Ensure that there are zero messages on the local broker. This tells
    // us that those messages have been prefetched to the remote broker
    // where the demand exists.
    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            Object[] result = browseQueueWithJmx(localBroker);
            return 0 == result.length;
        }
    });
    messages = browseQueueWithJmx(localBroker);
    assertEquals(0, messages.length);

    // try and pull the messages from remote, should be denied b/c on networkTtl
    LOG.info("creating demand on second remote...");
    StubConnection connection3 = createSecondRemoteConnection();
    ConnectionInfo connectionInfo3 = createConnectionInfo();
    SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3);
    connection3.send(connectionInfo3);
    connection3.send(sessionInfo3);
    ActiveMQDestination destinationInfo3 = createDestinationInfo(connection3, connectionInfo3,
            ActiveMQDestination.QUEUE_TYPE);
    final ConsumerInfo consumerInfoS3 = createConsumerInfo(sessionInfo3, destinationInfo3);
    connection3.send(consumerInfoS3);

    Message messageExceedingTtl = receiveMessage(connection3, 5000);
    if (messageExceedingTtl != null) {
        LOG.error("got message on Second remote: " + messageExceedingTtl);
        connection3.send(createAck(consumerInfoS3, messageExceedingTtl, 1, MessageAck.INDIVIDUAL_ACK_TYPE));
    }

    LOG.info("Closing consumer on remote");
    // Close the consumer on the remote broker
    connection2.send(consumerInfo2.createRemoveCommand());
    // also close connection etc.. so messages get dropped from the local consumer  q
    connection2.send(connectionInfo2.createRemoveCommand());

    // There should now be 5 messages stuck on the remote broker
    assertTrue("correct stuck message count", Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            Object[] result = browseQueueWithJmx(remoteBroker);
            return 5 == result.length;
        }
    }));
    messages = browseQueueWithJmx(remoteBroker);
    assertEquals(5, messages.length);

    assertTrue("can see broker path property", ((String) ((CompositeData) messages[1]).get("BrokerPath"))
            .contains(localBroker.getBroker().getBrokerId().toString()));

    LOG.info("Messages now stuck on remote");

    // receive again on the origin broker
    ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destinationInfo1);
    connection1.send(consumerInfo1);
    LOG.info("create local consumer: " + consumerInfo1);

    Message message1 = receiveMessage(connection1, 20000);
    assertNotNull("Expect to get a replay as remote consumer is gone", message1);
    connection1.send(createAck(consumerInfo1, message1, 1, MessageAck.INDIVIDUAL_ACK_TYPE));
    LOG.info("acked one message on origin, waiting for all messages to percolate back");

    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            Object[] result = browseQueueWithJmx(localBroker);
            return 4 == result.length;
        }
    });
    messages = browseQueueWithJmx(localBroker);
    assertEquals(4, messages.length);

    LOG.info("checking for messages on remote again");
    // messages won't migrate back again till consumer closes
    connection2 = createRemoteConnection();
    connectionInfo2 = createConnectionInfo();
    sessionInfo2 = createSessionInfo(connectionInfo2);
    connection2.send(connectionInfo2);
    connection2.send(sessionInfo2);
    ConsumerInfo consumerInfo3 = createConsumerInfo(sessionInfo2, destinationInfo2);
    connection2.send(consumerInfo3);
    message1 = receiveMessage(connection2, 20000);
    assertNull("Messages have migrated back: " + message1, message1);

    // Consume the last 4 messages from the local broker and ack them just
    // to clean up the queue.
    int counter = 1;
    for (; counter < receiveNumMessages; counter++) {
        message1 = receiveMessage(connection1);
        LOG.info("local consume of: " + (message1 != null ? message1.getMessageId() : " null"));
        connection1.send(createAck(consumerInfo1, message1, 1, MessageAck.INDIVIDUAL_ACK_TYPE));
    }
    // Ensure that 5 messages were received
    assertEquals(receiveNumMessages, counter);

    // verify all messages consumed
    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            Object[] result = browseQueueWithJmx(remoteBroker);
            return 0 == result.length;
        }
    });
    messages = browseQueueWithJmx(remoteBroker);
    assertEquals(0, messages.length);

    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            Object[] result = browseQueueWithJmx(localBroker);
            return 0 == result.length;
        }
    });
    messages = browseQueueWithJmx(localBroker);
    assertEquals(0, messages.length);

    // Close the consumer on the remote broker
    connection2.send(consumerInfo3.createRemoveCommand());

    connection1.stop();
    connection2.stop();
    connection3.stop();
}

From source file:net.timewalker.ffmq4.local.destination.LocalQueue.java

/**
 * Unlock a message./*from  www  .j av a2  s  .  c o  m*/
 * Listeners are automatically notified of the new message availability.
 */
public void unlockAndDeliver(MessageLock lockRef) throws JMSException {
    MessageStore targetStore;
    if (lockRef.getDeliveryMode() == DeliveryMode.NON_PERSISTENT)
        targetStore = volatileStore;
    else
        targetStore = persistentStore;

    int handle = lockRef.getHandle();
    AbstractMessage message = lockRef.getMessage();
    synchronized (storeLock) {
        targetStore.unlock(handle);
    }
    sentToQueueCount.incrementAndGet();

    sendAvailabilityNotification(message);
}

From source file:org.perfcake.message.sender.JmsSenderTest.java

@Test
public void testNonPersistentDelivery() throws Exception {
    final Properties props = new Properties();
    props.setProperty("messagetType", "STRING");
    props.setProperty("target", "queue/test");
    props.setProperty("persistent", "false");

    final JmsSender sender = (JmsSender) ObjectFactory.summonInstance(JmsSender.class.getName(), props);

    Assert.assertEquals(sender.isPersistent(), false);

    try {//  ww w .  j  a v  a2 s . c o m
        sender.init();

        // make sure the destination is empty
        Assert.assertNull(JmsHelper.readMessage(factory, 500, queue));

        // NON-PERSISTENT delivery
        final org.perfcake.message.Message message = new org.perfcake.message.Message();
        final String payload1 = "Hello World!";
        message.setPayload(payload1);
        sender.preSend(message, null, null);
        sender.send(message, null);
        sender.postSend(message);

        final Message response = JmsHelper.readMessage(factory, 500, queue);
        Assert.assertEquals(response.getJMSDeliveryMode(), DeliveryMode.NON_PERSISTENT);
        Assert.assertTrue(response instanceof TextMessage);
        Assert.assertEquals(((TextMessage) response).getText(), payload1);

        // make sure the destination is empty
        Assert.assertNull(JmsHelper.readMessage(factory, 500, queue));
    } finally {
        sender.close();
    }
}

From source file:de.klemp.middleware.controller.Controller.java

public static void sendMessageFast(String message, String topic) {
    String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

    // Create a Connection
    Connection connection;/*from  w w w.  j ava 2  s  .c o m*/
    try {
        connectionFactory.setOptimizeAcknowledge(true);
        connectionFactory.setUseAsyncSend(true);
        connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // Create the destination (Topic or Queue)
        Destination destination = session.createTopic(topic);
        // Create a MessageProducer from the Session to the Topic or Queue
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        // Create a messages
        TextMessage message1 = session.createTextMessage(message);
        // Tell the producer to send the message
        producer.send(message1);
        session.close();
        connection.close();
    } catch (JMSException e) {
        logger.error("Message could not be sended to activemq", e);
    }

}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public void createProducer(final CreateProducerCommand command) {
    try {//from  www  . ja  v a2  s  . c o  m
        final Session session = _testSessions.get(command.getSessionName());
        if (session == null) {
            throw new DistributedTestException("No test session found called: " + command.getSessionName(),
                    command);
        }

        synchronized (session) {
            final Destination destination;
            if (command.isTopic()) {
                destination = session.createTopic(command.getDestinationName());
            } else {
                destination = session.createQueue(command.getDestinationName());
            }

            final MessageProducer jmsProducer = session.createProducer(destination);

            if (command.getPriority() != -1) {
                jmsProducer.setPriority(command.getPriority());
            }
            if (command.getTimeToLive() > 0) {
                jmsProducer.setTimeToLive(command.getTimeToLive());
            }

            if (command.getDeliveryMode() == DeliveryMode.NON_PERSISTENT
                    || command.getDeliveryMode() == DeliveryMode.PERSISTENT) {
                jmsProducer.setDeliveryMode(command.getDeliveryMode());
            }

            addProducer(command.getParticipantName(), jmsProducer);
        }
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to create new producer: " + command, jmse);
    }
}

From source file:net.timewalker.ffmq4.local.destination.LocalQueue.java

/**
 * Remove a locked message from this queue. The message is deleted from the underlying store.
 *///ww  w .  j av  a 2s.c  o m
public void removeLocked(MessageLock lockRef) throws JMSException {
    checkTransactionLock();

    MessageStore targetStore;
    if (lockRef.getDeliveryMode() == DeliveryMode.NON_PERSISTENT)
        targetStore = volatileStore;
    else {
        targetStore = persistentStore;
        if (requiresTransactionalUpdate())
            pendingChanges = true;
    }

    synchronized (storeLock) {
        targetStore.delete(lockRef.getHandle());
    }
}