Java 类javax.jms.DeliveryMode 实例源码

项目:axon-jms    文件:JmsPublisherTest.java   
@Test
public void testSendPersistentMessage() throws Exception {
  cut.setPersistent(true);
  cut.setMessageConverter(null);
  cut.postConstruct();

  TopicConnection connection = mock(TopicConnection.class);
  when(connectionFactory.createTopicConnection()).thenReturn(connection);
  TopicSession transactionalSession = mock(TopicSession.class);

  when(connection.createTopicSession(true, Session.SESSION_TRANSACTED))
      .thenReturn(transactionalSession);
  when(transactionalSession.createPublisher(topic)).thenReturn(publisher);
  TextMessage jmsMessage = mock(TextMessage.class);
  when(transactionalSession.createTextMessage(any())).thenReturn(jmsMessage);
  ArgumentCaptor<Message> jmsMsgCapture = ArgumentCaptor.forClass(Message.class);
  doNothing().when(publisher).publish(jmsMsgCapture.capture());

  eventBus.publish(new GenericEventMessage<>("Message"));

  verify(jmsMessage).setJMSDeliveryMode(DeliveryMode.PERSISTENT);
}
项目:karate    文件:QueueUtils.java   
public static void send(String queueName, String text, int delayMillis) {
    EXECUTOR.submit(() -> {
        try {
            logger.info("*** artificial delay {}: {}", queueName, delayMillis);
            Thread.sleep(delayMillis);
            Connection connection = getConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue(queueName);
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            TextMessage message = session.createTextMessage(text);
            producer.send(message);
            logger.info("*** sent message {}: {}", queueName, text);
            session.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });
}
项目:oneops    文件:SensorPublisher.java   
/**
 * Publish message.
 *
 * @param event the event
 * @throws JMSException the jMS exception
 */
public void publishMessage(final BasicEvent event) throws JMSException {

    if (System.currentTimeMillis() > lastFailureTimestamp) {
        publishedCounter.incrementAndGet();
        int shard = (int) (event.getManifestId() % poolsize);
        try {
            producers[shard].send(session -> {
                ObjectMessage message = session.createObjectMessage(event);
                message.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
                message.setLongProperty("ciId", event.getCiId());
                message.setLongProperty("manifestId", event.getManifestId());
                message.setStringProperty("source", event.getSource());
                if (logger.isDebugEnabled()) {
                    logger.debug("Published: ciId:" + event.getCiId() + "; source:" + event.getSource());
                }
                return message;
            });
            lastFailureTimestamp = -1;
        } catch (JmsException exception) {
            logger.warn("There was an error sending a message. Discarding messages for " + mqConnectionThreshold + " ms");
            lastFailureTimestamp = System.currentTimeMillis() + mqConnectionThreshold;
        }
    }
}
项目:xsharing-services-router    文件:DetailsCaller.java   
public String sendRequest(Optional<String> routeId) {
    DetailsRequest req = new DetailsRequest(routeId.orElse("asdf"));
    try {
        TextMessage msg = context.createTextMessage(JsonMapper.serializeOrThrow(req));
        msg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);

        Queue answerQ = context.createTemporaryQueue();
        msg.setJMSReplyTo(answerQ);

        context.createProducer().send(minQ, msg);

        Message response = context.createConsumer(answerQ).receive();
        if (response instanceof TextMessage) {
            return ((TextMessage) response).getText();
        }

        return "";
    } catch (JMSException e) {
        return e.getMessage();
    }
}
项目:xsharing-services-router    文件:CompactCaller.java   
public String sendRequest(Optional<String> routeId) {
    CompactRequest req = new CompactRequest(routeId.orElse("asdf"));
    try {
        TextMessage msg = context.createTextMessage(JsonMapper.serializeOrThrow(req));
        msg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);

        Queue answerQ = context.createTemporaryQueue();
        msg.setJMSReplyTo(answerQ);

        context.createProducer().send(minQ, msg);

        Message response = context.createConsumer(answerQ).receive();
        if (response instanceof TextMessage) {
            return ((TextMessage) response).getText();
        }

        return "";
    } catch (JMSException e) {
        return e.getMessage();
    }
}
项目:xsharing-services-router    文件:AbstractSharingListener.java   
private void wrapAndSendResponseInternal(Message incoming, List<B> response) throws JMSException {
    String text;
    try {
        text = JsonMapper.serialize(response);
    } catch (JsonProcessingException e) {
        getLogger().warn("Failed to convert response to text. Will not send response");
        return;
    }

    getLogger().debug("Response (object): {}", response);
    getLogger().debug("Response (string): {}", text);

    TextMessage msg = getContext().createTextMessage(text);
    msg.setJMSCorrelationID(incoming.getJMSCorrelationID());

    getContext().createProducer()
                .setDisableMessageID(true)
                .setDisableMessageTimestamp(true)
                .setDeliveryMode(DeliveryMode.NON_PERSISTENT)
                .send(incoming.getJMSReplyTo(), msg);
}
项目:spring4-understanding    文件:SimpleJmsHeaderMapperTests.java   
@Test
public void jmsReadOnlyPropertiesNotMapped() throws JMSException {
    Message<String> message = initBuilder()
            .setHeader(JmsHeaders.DESTINATION, new Destination() {})
            .setHeader(JmsHeaders.DELIVERY_MODE, DeliveryMode.NON_PERSISTENT)
            .setHeader(JmsHeaders.EXPIRATION, 1000L)
            .setHeader(JmsHeaders.MESSAGE_ID, "abc-123")
            .setHeader(JmsHeaders.PRIORITY, 9)
            .setHeader(JmsHeaders.REDELIVERED, true)
            .setHeader(JmsHeaders.TIMESTAMP, System.currentTimeMillis())
            .build();
    javax.jms.Message jmsMessage = new StubTextMessage();
    mapper.fromHeaders(message.getHeaders(), jmsMessage);
    assertNull(jmsMessage.getJMSDestination());
    assertEquals(DeliveryMode.PERSISTENT, jmsMessage.getJMSDeliveryMode());
    assertEquals(0, jmsMessage.getJMSExpiration());
    assertNull(jmsMessage.getJMSMessageID());
    assertEquals(javax.jms.Message.DEFAULT_PRIORITY, jmsMessage.getJMSPriority());
    assertFalse(jmsMessage.getJMSRedelivered());
    assertEquals(0, jmsMessage.getJMSTimestamp());
}
项目:JSearcher    文件:Sender.java   
/**
 * 
 * @param queue_name : name of destination message queue
 * @param host_name : destination ip/host name
 */
public Sender(String queue_name, String host_name) {
    connectionFactory = new ActiveMQConnectionFactory(
               ActiveMQConnection.DEFAULT_USER,
               ActiveMQConnection.DEFAULT_PASSWORD,
               "tcp://" + host_name +":61616");

       try {
           connection = connectionFactory.createConnection();
           connection.start();
           session = connection.createSession(Boolean.TRUE,
                   Session.AUTO_ACKNOWLEDGE);      
           destination = session.createQueue(queue_name);
           producer = session.createProducer(destination);
           producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

       } catch (JMSException je) {
           je.printStackTrace();
       } 

}
项目:iws    文件:NotificationEmailSender.java   
private void initializeQueue() {
    Context context = null;

    try {
        context = new InitialContext();
        final QueueConnectionFactory factory = (QueueConnectionFactory) context.lookup(QUEUE_FACTORY_NAME);
        queueConnection = factory.createQueueConnection();
        queueConnection.start();

        final Queue queue = (Queue) context.lookup(QUEUE_NAME);

        session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        sender = session.createSender(queue);
        sender.setDeliveryMode(DeliveryMode.PERSISTENT);
    } catch (NamingException | JMSException e) {
        throw new IWSException(IWSErrors.ERROR, "Queue sender (NotificationEmailSender) initialization failed.", e);
    } finally {
        close(context);
    }
}
项目:c2mon    文件:JmsProxyImpl.java   
@Override
public void publish(final String message, final String topicName, final long timeToLive) throws JMSException {
  if (topicName == null) {
    throw new NullPointerException("publish(..) method called with null queue name argument");
  }
  if (message == null) {
    throw new NullPointerException("publish(..) method called with null message argument");
  }
  if (connected) {
    final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    try {
      final Message messageObj = session.createTextMessage(message);

      final MessageProducer producer = session.createProducer(new ActiveMQTopic(topicName));
      producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
      producer.setTimeToLive(JMS_MESSAGE_TIMEOUT);
      producer.send(messageObj);
    } finally {
      session.close();
    }
  } else {
    throw new JMSException("Not currently connected: unable to send message at this time.");
  }
}
项目:boteco    文件:DefaultJmsMessageConfiguration.java   
@Override
public void to(JmsDestination target) {
  try {
    Connection connection = connectionFactory.createConnection();
    connection.start();

    Session session = createFunction.apply(connection);
    Destination destination = target.createDestination(session);

    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    if (this.expirationTime != null) {
      producer.setTimeToLive(this.expirationTime);
    }

    ObjectMessage message = session.createObjectMessage(object);
    producer.send(message);

    session.close();
    connection.close();
  } catch (JMSException e) {
    logger.error("Error while sending object to AMQ destination", e);
  }
}
项目:apex-malhar    文件:JMSObjectInputOperatorTest.java   
private void produceMsg() throws Exception
{
  // Create a ConnectionFactory
  ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

  // Create a Connection
  testMeta.connection = connectionFactory.createConnection();
  testMeta.connection.start();

  // Create a Session
  testMeta.session = testMeta.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

  // Create the destination (Topic or Queue)
  Destination destination = testMeta.session.createQueue("TEST.FOO");

  // Create a MessageProducer from the Session to the Topic or Queue
  testMeta.producer = testMeta.session.createProducer(destination);
  testMeta.producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
项目:activemq-artemis    文件:DurableSubscriptionTestSupport.java   
public void testMessageExpire() throws Exception {
   session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
   Topic topic = session.createTopic("TestTopic");
   consumer = session.createDurableSubscriber(topic, "sub1");
   producer = session.createProducer(topic);
   producer.setDeliveryMode(DeliveryMode.PERSISTENT);
   producer.setTimeToLive(1000);
   connection.start();

   // Make sure it works when the durable sub is active.
   producer.send(session.createTextMessage("Msg:1"));
   assertTextMessageEquals("Msg:1", consumer.receive(1000));

   consumer.close();

   producer.send(session.createTextMessage("Msg:2"));
   producer.send(session.createTextMessage("Msg:3"));

   consumer = session.createDurableSubscriber(topic, "sub1");

   // Try to get the message.
   assertTextMessageEquals("Msg:2", consumer.receive(1000));
   Thread.sleep(1000);
   assertNull(consumer.receive(1000));
}
项目:activemq-artemis    文件:JmsQueueTopicCompositeSendReceiveTest.java   
/**
 * Sets a test to have a queue destination and non-persistent delivery mode.
 *
 * @see junit.framework.TestCase#setUp()
 */
@Override
protected void setUp() throws Exception {
   deliveryMode = DeliveryMode.NON_PERSISTENT;
   topic = false;
   super.setUp();
   consumerDestination2 = consumeSession.createTopic("FOO.BAR.HUMBUG2");
   LOG.info("Created  consumer destination: " + consumerDestination2 + " of type: " + consumerDestination2.getClass());
   if (durable) {
      LOG.info("Creating durable consumer");
      consumer2 = consumeSession.createDurableSubscriber((Topic) consumerDestination2, getName());
   } else {
      consumer2 = consumeSession.createConsumer(consumerDestination2);
   }

}
项目:hadoop-mini-clusters    文件:ActivemqLocalBroker.java   
@Override
public void start() throws Exception {
    String uri = uriPrefix + hostName + ":" + port;
    LOG.info("ACTIVEMQ: Starting ActiveMQ on {}", uri);
    configure();

    broker = new BrokerService();
    broker.addConnector(uri);
    broker.start();

    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(uri + uriPostfix);
    Connection conn = factory.createConnection();
    conn.start();

    session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    dest = session.createQueue(queueName);
    consumer = session.createConsumer(dest);
    producer = session.createProducer(dest);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
项目:carbon-transports    文件:JMSServer.java   
/**
 * To publish the messages to a queue.
 *
 * @throws JMSException         JMS Exception.
 * @throws InterruptedException Interrupted exception while waiting in between messages.
 */
public void publishMessagesToQueue(String queueName) throws JMSException, InterruptedException {
    QueueConnection queueConn = (QueueConnection) connectionFactory.createConnection();
    queueConn.start();
    QueueSession queueSession = queueConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = queueSession.createQueue(queueName);
    MessageProducer queueSender = queueSession.createProducer(destination);
    queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    for (int index = 0; index < 10; index++) {
        String queueText = "Queue Message : " + (index + 1);
        TextMessage queueMessage = queueSession.createTextMessage(queueText);
        queueSender.send(queueMessage);
        Thread.sleep(1000);
        logger.info("Publishing " + queueText + " to queue " + queueName);
    }
    queueConn.close();
    queueSession.close();
    queueSender.close();
}
项目:activemq-artemis    文件:JmsTempDestinationTest.java   
/**
 * Make sure that a temp queue does not drop message if there is an active
 * consumers.
 *
 * @throws JMSException
 */
@Test
public void testTempQueueHoldsMessagesWithConsumers() throws JMSException {
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createTemporaryQueue();
   MessageConsumer consumer = session.createConsumer(queue);
   connection.start();

   MessageProducer producer = session.createProducer(queue);
   producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
   TextMessage message = session.createTextMessage("Hello");
   producer.send(message);

   Message message2 = consumer.receive(1000);
   Assert.assertNotNull(message2);
   Assert.assertTrue("Expected message to be a TextMessage", message2 instanceof TextMessage);
   Assert.assertTrue("Expected message to be a '" + message.getText() + "'", ((TextMessage) message2).getText().equals(message.getText()));
}
项目:activemq-artemis    文件:JMSContextExample.java   
public static void main(final String[] args) throws Exception {
   // Instantiate the queue
   Queue queue = ActiveMQJMSClient.createQueue("exampleQueue");

   // Instantiate the ConnectionFactory (Using the default URI on this case)
   // Also instantiate the jmsContext
   // Using closeable interface
   try (ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory();
        JMSContext jmsContext = cf.createContext()) {
      // Create a message producer, note that we can chain all this into one statement
      jmsContext.createProducer().setDeliveryMode(DeliveryMode.PERSISTENT).send(queue, "this is a string");

      // Create a Consumer and receive the payload of the message direct.
      String payLoad = jmsContext.createConsumer(queue).receiveBody(String.class);

      System.out.println("payLoad = " + payLoad);

   }

}
项目:activemq-artemis    文件:MultipleProducersTest.java   
private void sendMessage(Queue queue, Session session) throws Exception {

      MessageProducer mp = session.createProducer(queue);

      try {
         mp.setDisableMessageID(true);
         mp.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
         mp.setPriority(Message.DEFAULT_PRIORITY);
         mp.setTimeToLive(Message.DEFAULT_TIME_TO_LIVE);

         mp.send(session.createTextMessage("This is message for " + queue.getQueueName()));
      } finally {

         mp.close();
      }
   }
项目:activemq-artemis    文件:JmsSendWithAsyncCallbackTest.java   
private double benchmarkCallbackRate() throws JMSException, InterruptedException {
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createQueue(getName());
   int count = 1000;
   final CountDownLatch messagesSent = new CountDownLatch(count);
   ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(queue);
   producer.setDeliveryMode(DeliveryMode.PERSISTENT);
   long start = System.currentTimeMillis();
   for (int i = 0; i < count; i++) {
      producer.send(session.createTextMessage("Hello"), new AsyncCallback() {
         @Override
         public void onSuccess() {
            messagesSent.countDown();
         }

         @Override
         public void onException(JMSException exception) {
            exception.printStackTrace();
         }
      });
   }
   messagesSent.await();
   return 1000.0 * count / (System.currentTimeMillis() - start);
}
项目:activemq-artemis    文件:CompressionOverNetworkTest.java   
@Test
public void testCompressedOverCompressedNetwork() throws Exception {

   ActiveMQConnection localAmqConnection = (ActiveMQConnection) localConnection;
   localAmqConnection.setUseCompression(true);

   MessageConsumer consumer1 = remoteSession.createConsumer(included);
   MessageProducer producer = localSession.createProducer(included);
   producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

   waitForConsumerRegistration(localBroker, 1, included);

   StringBuilder payload = new StringBuilder("test-");
   for (int i = 0; i < 100; ++i) {
      payload.append(UUID.randomUUID().toString());
   }

   Message test = localSession.createTextMessage(payload.toString());
   producer.send(test);
   Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS);
   assertNotNull(msg);
   ActiveMQTextMessage message = (ActiveMQTextMessage) msg;
   assertTrue(message.isCompressed());
   assertEquals(payload.toString(), message.getText());
}
项目:activemq-artemis    文件:AcknowledgementTest.java   
/**
 * Topics shouldn't hold on to messages when the non-durable subscribers close
 */
@Test
public void testPersistentMessagesForTopicDropped2() throws Exception {
   TopicConnection topicConn = createTopicConnection();
   topicConn.start();
   TopicSession sess = topicConn.createTopicSession(true, 0);
   TopicPublisher pub = sess.createPublisher(ActiveMQServerTestCase.topic1);
   TopicSubscriber sub = sess.createSubscriber(ActiveMQServerTestCase.topic1);
   pub.setDeliveryMode(DeliveryMode.PERSISTENT);

   Message m = sess.createTextMessage("testing123");
   pub.publish(m);
   sess.commit();

   // receive but rollback
   TextMessage m2 = (TextMessage) sub.receive(3000);

   ProxyAssertSupport.assertNotNull(m2);
   ProxyAssertSupport.assertEquals("testing123", m2.getText());

   sess.rollback();

   topicConn.close();

   checkEmpty(ActiveMQServerTestCase.topic1);
}
项目:activemq-artemis    文件:CriticalAnalyzerFaultInjectionTestBase.java   
void testSendDurableMessage() throws Exception {
   try {
      t = new Thread(() -> {
         try {
            Session s = conn.createSession(true, Session.SESSION_TRANSACTED);

            Queue jmsQueue = s.createQueue(address.toString());
            MessageProducer p = s.createProducer(jmsQueue);
            p.setDeliveryMode(DeliveryMode.PERSISTENT);
            conn.start();
            for (int i = 0; i < 10; i++) {
               p.send(s.createTextMessage("payload"));
            }
            s.commit();
         } catch (Throwable e) {
            e.printStackTrace();
         }
      });
      t.start();

      Wait.assertFalse(server::isStarted);
   } finally {
      t.interrupt();
   }
}
项目:activemq-artemis    文件:DurableSubscriptionTestSupport.java   
public void testDurableSubscriptionBrokerRestart() throws Exception {

      // Create the durable sub.
      connection.start();
      session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

      // Ensure that consumer will receive messages sent before it was created
      Topic topic = session.createTopic("TestTopic?consumer.retroactive=true");
      consumer = session.createDurableSubscriber(topic, "sub1");

      producer = session.createProducer(topic);
      producer.setDeliveryMode(DeliveryMode.PERSISTENT);
      producer.send(session.createTextMessage("Msg:1"));
      assertTextMessageEquals("Msg:1", consumer.receive(5000));

      // Make sure cleanup kicks in
      Thread.sleep(1000);

      // Restart the broker.
      restartBroker();
   }
项目:pooled-jms    文件:JmsPoolJMSProducer.java   
@Override
public JMSProducer setDeliveryMode(int deliveryMode) {
    switch (deliveryMode) {
        case DeliveryMode.PERSISTENT:
        case DeliveryMode.NON_PERSISTENT:
            this.deliveryMode = deliveryMode;
            return this;
        default:
            throw new JMSRuntimeException(String.format("Invalid DeliveryMode specified: %d", deliveryMode));
    }
}
项目:pooled-jms    文件:JmsPoolJMSProducerTest.java   
@Test
public void testDeliveryMode() {
    JMSProducer producer = context.createProducer();

    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    assertEquals(DeliveryMode.PERSISTENT, producer.getDeliveryMode());
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    assertEquals(DeliveryMode.NON_PERSISTENT, producer.getDeliveryMode());
}
项目:pooled-jms    文件:JmsPoolJMSProducerTest.java   
public void doTestSendAppliesDeliveryModeWithMessageBody(Class<?> bodyType) throws JMSException {
    JMSProducer producer = context.createProducer();

    final AtomicBoolean nonPersistentMessage = new AtomicBoolean();
    final AtomicBoolean persistentMessage = new AtomicBoolean();

    MockJMSConnection connection = (MockJMSConnection) context.getConnection();
    connection.addConnectionListener(new MockJMSDefaultConnectionListener() {

        @Override
        public void onMessageSend(MockJMSSession session, Message message) throws JMSException {
            if (!persistentMessage.get()) {
                assertEquals(DeliveryMode.PERSISTENT, message.getJMSDeliveryMode());
                persistentMessage.set(true);
            } else {
                assertEquals(DeliveryMode.NON_PERSISTENT, message.getJMSDeliveryMode());
                nonPersistentMessage.set(true);
            }
        }
    });

    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    producer.send(JMS_DESTINATION, "text");

    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    producer.send(JMS_DESTINATION, "text");

    assertTrue(persistentMessage.get());
    assertTrue(nonPersistentMessage.get());
}
项目:pooled-jms    文件:MockJMSMessage.java   
@Override
public void setJMSDeliveryMode(int deliveryMode) throws JMSException {
    switch (deliveryMode) {
        case DeliveryMode.PERSISTENT:
            persistent = true;
            break;
        case DeliveryMode.NON_PERSISTENT:
            persistent = false;
            break;
        default:
            throw new JMSException(String.format("Invalid DeliveryMode specific: %d", deliveryMode));
    }
}
项目:pooled-jms    文件:MockJMSMessageProducer.java   
@Override
public void setDeliveryMode(int deliveryMode) throws JMSException {
    checkClosed();
    switch (deliveryMode) {
        case DeliveryMode.PERSISTENT:
        case DeliveryMode.NON_PERSISTENT:
            this.deliveryMode = deliveryMode;
            break;
        default:
            throw new JMSException(String.format("Invalid DeliveryMode specified: %d", deliveryMode));
    }
}
项目:pooled-jms    文件:MockJMSProducer.java   
@Override
public JMSProducer setDeliveryMode(int deliveryMode) {
    switch (deliveryMode) {
        case DeliveryMode.PERSISTENT:
        case DeliveryMode.NON_PERSISTENT:
            this.deliveryMode = deliveryMode;
            return this;
        default:
            throw new JMSRuntimeException(String.format("Invalid DeliveryMode specified: %d", deliveryMode));
    }
}
项目:SpringTutorial    文件:HelloWorldProducer.java   
public static void main(String[] args) {

        try {
            // Create a ConnectionFactory
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://Toshiba:61616");

            // Create a Connection
            Connection connection = connectionFactory.createConnection();
            connection.start();

            // Create a Session
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // Create the destination (Topic or Queue)
            Destination destination = session.createQueue("HELLOWORLD.TESTQ");

            // Create a MessageProducer from the Session to the Topic or Queue
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

            // Create a messages
            String text = "Hello world! From: " + Thread.currentThread().getName();
            TextMessage message = session.createTextMessage(text);

            // Tell the producer to send the message
            System.out.println("Sent message: "+ message.hashCode() + " : " + Thread.currentThread().getName());
            producer.send(message);

            // Clean up
            session.close();
            connection.close();
        }
        catch (Exception e) {
            System.out.println("Caught: " + e);
            e.printStackTrace();
        }

    }
项目:SpringTutorial    文件:HelloWorldProducerThread.java   
public void run() {
    try {
        // Create a ConnectionFactory
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://Toshiba:61616");

        // Create a Connection
        Connection connection = connectionFactory.createConnection();
        connection.start();

        // Create a Session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Create the destination (Topic or Queue)
        Destination destination = session.createQueue("HELLOWORLD.TESTQ");

        // Create a MessageProducer from the Session to the Topic or Queue
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        // Create a messages
        String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode();
        TextMessage message = session.createTextMessage(text);

        // Tell the producer to send the message
        System.out.println("Sent message: "+ message.hashCode() + " : " + Thread.currentThread().getName());
        producer.send(message);

        // Clean up
        session.close();
        connection.close();
    }
    catch (Exception e) {
        System.out.println("Caught: " + e);
        e.printStackTrace();
    }
}
项目:axon-jms    文件:DefaultJmsMessageConverter.java   
@Override
public Message createJmsMessage(EventMessage<?> eventMessage, Session session)
        throws JMSException {

  SerializedObject<String> serializedObject
          = serializer.serialize(eventMessage.getPayload(), String.class);
  TextMessage jmsMessage = session.createTextMessage(serializedObject.getData());
  for (Map.Entry<String, Object> entry : eventMessage.getMetaData().entrySet()) {
    jmsMessage.setObjectProperty(
            "axon-metadata-" + entry.getKey(), entry.getValue());
  }
  jmsMessage.setObjectProperty("axon-message-id", eventMessage.getIdentifier());
  jmsMessage.setObjectProperty("axon-message-type", serializedObject.getType().getName());
  jmsMessage.setObjectProperty("axon-message-revision", serializedObject.getType().getRevision());
  jmsMessage.setObjectProperty("axon-message-timestamp", eventMessage.getTimestamp().toString());
  if (eventMessage instanceof DomainEventMessage) {
    jmsMessage.setObjectProperty("axon-message-aggregate-id",
            ((DomainEventMessage) eventMessage).getAggregateIdentifier());
    jmsMessage.setObjectProperty("axon-message-aggregate-seq",
            ((DomainEventMessage) eventMessage).getSequenceNumber());
    jmsMessage.setObjectProperty("axon-message-aggregate-type",
            ((DomainEventMessage) eventMessage).getType());
  }
  if (persistent) {
    jmsMessage.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
  }
  return jmsMessage;
}
项目:scanning    文件:PublisherImpl.java   
protected void send(MessageProducer producer, Object message, long messageLifetime)  throws Exception {

        int priority = message instanceof ConsumerCommandBean ? 8 : 4;

        String json = service.marshal(message);
        TextMessage msg = createTextMessage(json);
        producer.send(msg, DeliveryMode.NON_PERSISTENT, priority, messageLifetime);
        if (out!=null) out.println(json);
    }
项目:java-jms    文件:TracingActiveMQTest.java   
@Test
public void sendAndReceive() throws Exception {
  Destination destination = session.createQueue("TEST.FOO");

  MessageProducer messageProducer = session.createProducer(destination);
  messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

  // Instrument MessageProducer with TracingMessageProducer
  TracingMessageProducer producer =
      new TracingMessageProducer(messageProducer, mockTracer);

  MessageConsumer messageConsumer = session.createConsumer(destination);

  // Instrument MessageConsumer with TracingMessageConsumer
  TracingMessageConsumer consumer = new TracingMessageConsumer(messageConsumer, mockTracer);

  TextMessage message = session.createTextMessage("Hello world");

  producer.send(message);

  TextMessage received = (TextMessage) consumer.receive(5000);
  assertEquals("Hello world", received.getText());

  List<MockSpan> mockSpans = mockTracer.finishedSpans();
  assertEquals(2, mockSpans.size());

  checkSpans(mockSpans);
  assertNull(mockTracer.activeSpan());
}
项目:org.ops4j.pax.transx    文件:JMSProducerImpl.java   
@Override
public JMSProducer setDeliveryMode(int deliveryMode) {
    switch (deliveryMode) {
        case DeliveryMode.PERSISTENT:
        case DeliveryMode.NON_PERSISTENT:
            this.deliveryMode = deliveryMode;
            return this;
        default:
            throw new JMSRuntimeException(String.format("Invalid DeliveryMode specified: %d", deliveryMode));
    }
}
项目:oneops    文件:InductorPublisher.java   
private MessageProducer newMessageProducer(String queueName) throws JMSException {
    // Create the session
    Destination destination = session.createQueue(queueName);
    // Create the producer.
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    logger.info("Created message producer for queue " + queueName);
    return producer;
}
项目:oneops    文件:MonitorPublisher.java   
/**
 * Inits the.
 *
 * @throws JMSException the jMS exception
 */
public void init() throws JMSException {

    connection = connectionFactory.createConnection();
    connection.start();

    // Create the session
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue(QUEUE);
    // Create the producer.
    producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
   }
项目:oneops    文件:OpsEventPublisher.java   
/**
 * Inits the.
 *
 * @throws JMSException the jMS exception
 */
public void init() throws JMSException {

    connection = connectionFactory.createConnection();
    connection.start();

    // Create the session
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue(queue);
    // Create the producer.
    producer = session.createProducer(destination);

    if (persistent) {
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    } else {
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    }
    if (timeToLive != 0) {
        producer.setTimeToLive(timeToLive);
    }
   }
项目:xtf    文件:JmsClient.java   
public void sendMessage(Message message) throws JMSException {
    Connection connection = null;
    try {
        connection = startConnection(); //try to be smarter here and initiate start connection
        Session session = null;
        try {
            session = connection.createSession(isTransacted, Session.AUTO_ACKNOWLEDGE);
            Destination dest;
            if (isQueue) {
                dest = session.createQueue(destinationName);
            } else {
                dest = session.createTopic(destinationName);
            }
            MessageProducer producer = session.createProducer(dest);
            try {

                if (isPersistant) producer.setDeliveryMode(DeliveryMode.PERSISTENT);
                if (timeToLive > 0) producer.setTimeToLive(timeToLive);

                producer.send(message);
            } finally {
                if (producer != null) producer.close();
            }
        } finally {
            if (session != null) session.close();
        }
    } finally {
        safeCloseConnection(connection);
    }
}