Java Code Examples for org.springframework.jms.core.JmsTemplate

The following examples show how to use org.springframework.jms.core.JmsTemplate. These examples are extracted from open source projects. 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 Project: nifi   Source File: JMSPublisherConsumerIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * At the moment the only two supported message types are TextMessage and
 * BytesMessage which is sufficient for the type if JMS use cases NiFi is
 * used. The may change to the point where all message types are supported
 * at which point this test will no be longer required.
 */
@Test
public void validateFailOnUnsupportedMessageType() throws Exception {
    final String destinationName = "validateFailOnUnsupportedMessageType";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    try {
        jmsTemplate.send(destinationName, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createObjectMessage();
            }
        });

        JMSConsumer consumer = new JMSConsumer((CachingConnectionFactory) jmsTemplate.getConnectionFactory(), jmsTemplate, mock(ComponentLog.class));
        consumer.consume(destinationName, null, false, false, null, "UTF-8", new ConsumerCallback() {
            @Override
            public void accept(JMSResponse response) {
                // noop
            }
        });
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example 2
/**
 * At the moment the only two supported message types are TextMessage and
 * BytesMessage which is sufficient for the type if JMS use cases NiFi is
 * used. The may change to the point where all message types are supported
 * at which point this test will no be longer required.
 */
@Test(expected = IllegalStateException.class)
public void validateFailOnUnsupportedMessageType() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    jmsTemplate.send(destinationName, new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createObjectMessage();
        }
    });

    JMSConsumer consumer = new JMSConsumer(jmsTemplate, mock(ComponentLog.class));
    try {
        consumer.consume(destinationName, new ConsumerCallback() {
            @Override
            public void accept(JMSResponse response) {
                // noop
            }
        });
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example 3
Source Project: spring-analysis-note   Source File: JmsTransactionManagerTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testLazyTransactionalSession() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	tm.setLazyResourceRetrieval(true);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(con).close();
}
 
Example 4
Source Project: java-technology-stack   Source File: JmsTransactionManagerTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testTransactionRollback() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute(new SessionCallback<Void>() {
		@Override
		public Void doInJms(Session sess) {
			assertTrue(sess == session);
			return null;
		}
	});
	tm.rollback(ts);

	verify(session).rollback();
	verify(session).close();
	verify(con).close();
}
 
Example 5
@Test
public void validateBytesConvertedToBytesMessageOnSendOverJNDI() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsJndiTemplateForDestination(false);

    JMSPublisher publisher = new JMSPublisher(jmsTemplate, mock(ComponentLog.class));
    publisher.publish(destinationName, "hellomq".getBytes());

    Message receivedMessage = jmsTemplate.receive(destinationName);
    assertTrue(receivedMessage instanceof BytesMessage);
    byte[] bytes = new byte[7];
    ((BytesMessage) receivedMessage).readBytes(bytes);
    assertEquals("hellomq", new String(bytes));

    ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
}
 
Example 6
@Test
public void testDefaultsToLocalURI() {
    load(EmptyConfiguration.class);

    JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class);
    ConnectionFactory connectionFactory =
        this.context.getBean(ConnectionFactory.class);

    assertTrue(connectionFactory instanceof JmsConnectionFactory);

    JmsConnectionFactory qpidJmsFactory = (JmsConnectionFactory) connectionFactory;

    assertEquals(jmsTemplate.getConnectionFactory(), connectionFactory);
    assertEquals("amqp://localhost:5672", qpidJmsFactory.getRemoteURI());
    assertNull(qpidJmsFactory.getUsername());
    assertNull(qpidJmsFactory.getPassword());
}
 
Example 7
@Test
public void testReceiveLocalOnlyOptionsAppliedFromEnvOverridesURI() {
    load(EmptyConfiguration.class,
         "amqphub.amqp10jms.remote-url=amqp://127.0.0.1:5672" +
             "?jms.receiveLocalOnly=false&jms.receiveNoWaitLocalOnly=false",
         "amqphub.amqp10jms.receiveLocalOnly=true",
         "amqphub.amqp10jms.receiveNoWaitLocalOnly=true");

    JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class);
    JmsConnectionFactory connectionFactory =
        this.context.getBean(JmsConnectionFactory.class);

    assertEquals(jmsTemplate.getConnectionFactory(), connectionFactory);

    assertTrue(connectionFactory.isReceiveLocalOnly());
    assertTrue(connectionFactory.isReceiveNoWaitLocalOnly());
}
 
Example 8
Source Project: blackduck-alert   Source File: EventManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSendEvents() throws Exception {
    JmsTemplate jmsTemplate = Mockito.mock(JmsTemplate.class);
    ContentConverter contentConverter = Mockito.mock(ContentConverter.class);
    Mockito.doNothing().when(jmsTemplate).convertAndSend(Mockito.anyString(), Mockito.any(Object.class));
    EventManager eventManager = new EventManager(contentConverter, jmsTemplate);

    LinkableItem subTopic = new LinkableItem("subTopic", "sub topic", null);
    ProviderMessageContent content = new ProviderMessageContent.Builder()
                                         .applyProvider("provider", 1L, "providerConfig")
                                         .applyTopic("testTopic", "topic")
                                         .applySubTopic(subTopic.getName(), subTopic.getValue())
                                         .build();
    FieldAccessor fieldAccessor = new FieldAccessor(Map.of());
    DistributionEvent event = new DistributionEvent(UUID.randomUUID().toString(), "destination", RestConstants.formatDate(new Date()), "provider", "FORMAT",
        MessageContentGroup.singleton(content), fieldAccessor);
    eventManager.sendEvents(List.of(event));
}
 
Example 9
@Test
public void validateBytesConvertedToBytesMessageOnSend() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    JMSPublisher publisher = new JMSPublisher(jmsTemplate, mock(ComponentLog.class));
    publisher.publish(destinationName, "hellomq".getBytes());

    Message receivedMessage = jmsTemplate.receive(destinationName);
    assertTrue(receivedMessage instanceof BytesMessage);
    byte[] bytes = new byte[7];
    ((BytesMessage) receivedMessage).readBytes(bytes);
    assertEquals("hellomq", new String(bytes));

    ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
}
 
Example 10
/**
 * At the moment the only two supported message types are TextMessage and
 * BytesMessage which is sufficient for the type if JMS use cases NiFi is
 * used. The may change to the point where all message types are supported
 * at which point this test will no be longer required.
 */
@Test(expected = IllegalStateException.class)
public void validateFailOnUnsupportedMessageType() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    jmsTemplate.send(destinationName, new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createObjectMessage();
        }
    });

    JMSConsumer consumer = new JMSConsumer(jmsTemplate, mock(ComponentLog.class));
    try {
        consumer.consume(destinationName, new ConsumerCallback() {
            @Override
            public void accept(JMSResponse response) {
                // noop
            }
        });
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example 11
Source Project: nifi   Source File: AbstractJMSProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method essentially performs initialization of this Processor by
 * obtaining an instance of the {@link ConnectionFactory} from the
 * {@link JMSConnectionFactoryProvider} (ControllerService) and performing a
 * series of {@link ConnectionFactory} adaptations which eventually results
 * in an instance of the {@link CachingConnectionFactory} used to construct
 * {@link JmsTemplate} used by this Processor.
 */
private T buildTargetResource(ProcessContext context) {
    final ConnectionFactory connectionFactory = connectionFactoryProvider.getConnectionFactory();

    final UserCredentialsConnectionFactoryAdapter cfCredentialsAdapter = new UserCredentialsConnectionFactoryAdapter();
    cfCredentialsAdapter.setTargetConnectionFactory(connectionFactory);
    cfCredentialsAdapter.setUsername(context.getProperty(USER).evaluateAttributeExpressions().getValue());
    cfCredentialsAdapter.setPassword(context.getProperty(PASSWORD).getValue());

    final CachingConnectionFactory cachingFactory = new CachingConnectionFactory(cfCredentialsAdapter);
    setClientId(context, cachingFactory);

    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cachingFactory);
    jmsTemplate.setPubSubDomain(TOPIC.equals(context.getProperty(DESTINATION_TYPE).getValue()));

    return finishBuildingJmsWorker(cachingFactory, jmsTemplate, context);
}
 
Example 12
Source Project: nifi   Source File: JMSPublisherConsumerIT.java    License: Apache License 2.0 6 votes vote down vote up
private void testMessage(String destinationName, MessageCreator messageCreator, ConsumerCallback responseChecker) {
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    AtomicBoolean callbackInvoked = new AtomicBoolean();

    try {
        jmsTemplate.send(destinationName, messageCreator);

        JMSConsumer consumer = new JMSConsumer((CachingConnectionFactory) jmsTemplate.getConnectionFactory(), jmsTemplate, mock(ComponentLog.class));
        consumer.consume(destinationName, null, false, false, null, "UTF-8", response -> {
            callbackInvoked.set(true);
            responseChecker.accept(response);
        });

        assertTrue(callbackInvoked.get());
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example 13
Source Project: blackduck-alert   Source File: ChannelEventManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNotAbstractChannelEvent() throws Exception {
    AuditUtility auditUtility = Mockito.mock(AuditUtility.class);
    JmsTemplate jmsTemplate = Mockito.mock(JmsTemplate.class);
    ContentConverter contentConverter = Mockito.mock(ContentConverter.class);
    Mockito.doNothing().when(jmsTemplate).convertAndSend(Mockito.anyString(), Mockito.any(Object.class));
    ChannelEventManager eventManager = new ChannelEventManager(contentConverter, jmsTemplate, auditUtility);
    LinkableItem subTopic = new LinkableItem("subTopic", "sub topic", null);
    ProviderMessageContent content = new ProviderMessageContent.Builder()
                                         .applyProvider("testProvider", 1L, "testProviderConfig")
                                         .applyTopic("testTopic", "topic")
                                         .applySubTopic(subTopic.getName(), subTopic.getValue())
                                         .build();
    AlertEvent dbStoreEvent = new ContentEvent("", RestConstants.formatDate(new Date()), "", "FORMAT", MessageContentGroup.singleton(content));
    eventManager.sendEvent(dbStoreEvent);
}
 
Example 14
/**
 * This method essentially performs initialization of this Processor by
 * obtaining an instance of the {@link ConnectionFactory} from the
 * {@link JMSConnectionFactoryProvider} (ControllerService) and performing a
 * series of {@link ConnectionFactory} adaptations which eventually results
 * in an instance of the {@link CachingConnectionFactory} used to construct
 * {@link JmsTemplate} used by this Processor.
 */
private void buildTargetResource(ProcessContext context) {
    if (this.targetResource == null) {
        JMSConnectionFactoryProviderDefinition cfProvider = context.getProperty(CF_SERVICE).asControllerService(JMSConnectionFactoryProviderDefinition.class);
        ConnectionFactory connectionFactory = cfProvider.getConnectionFactory();

        UserCredentialsConnectionFactoryAdapter cfCredentialsAdapter = new UserCredentialsConnectionFactoryAdapter();
        cfCredentialsAdapter.setTargetConnectionFactory(connectionFactory);
        cfCredentialsAdapter.setUsername(context.getProperty(USER).getValue());
        cfCredentialsAdapter.setPassword(context.getProperty(PASSWORD).getValue());

        this.cachingConnectionFactory = new CachingConnectionFactory(cfCredentialsAdapter);
        this.cachingConnectionFactory.setSessionCacheSize(Integer.parseInt(context.getProperty(SESSION_CACHE_SIZE).getValue()));

        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory(this.cachingConnectionFactory);
        jmsTemplate.setPubSubDomain(TOPIC.equals(context.getProperty(DESTINATION_TYPE).getValue()));

        // set of properties that may be good candidates for exposure via configuration
        jmsTemplate.setReceiveTimeout(1000);

        this.targetResource = this.finishBuildingTargetResource(jmsTemplate, context);
    }
}
 
Example 15
@Bean
CommandLineRunner start(JmsTemplate template){
	return args -> {
		log.info("Sending> ...");
		template.convertAndSend(queue, "SpringBoot Rocks!");
	};
}
 
Example 16
Source Project: elephant   Source File: SessionAwareMessageListenerImpl.java    License: Apache License 2.0 5 votes vote down vote up
public SessionAwareMessageListenerImpl(Object bean, Method method,int retryTimes,boolean isRetry,JmsTemplate jmsTemplate) {
	this.bean = bean;
	this.method = method;
	this.retryTimes = retryTimes;
	this.isRetry = isRetry;
	this.jmsTemplate = jmsTemplate;
}
 
Example 17
Source Project: spring-analysis-note   Source File: JmsTransactionManagerTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testParticipatingTransactionWithCommit() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	final JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			jt.execute((SessionCallback<Void>) sess -> {
				assertSame(sess, session);
				return null;
			});
		}
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(con).close();
}
 
Example 18
Source Project: spring-jms   Source File: ProducingChannelConfig.java    License: MIT License 5 votes vote down vote up
@Bean
@ServiceActivator(inputChannel = "producingChannel")
public MessageHandler jmsMessageHandler(JmsTemplate jmsTemplate) {
  JmsSendingMessageHandler handler =
      new JmsSendingMessageHandler(jmsTemplate);
  handler.setDestinationName(integrationDestination);

  return handler;
}
 
Example 19
Source Project: spring-analysis-note   Source File: JmsTransactionManagerTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testTransactionCommitWithMessageProducer() throws JMSException {
	Destination dest = new StubQueue();

	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	Session session = mock(Session.class);
	MessageProducer producer = mock(MessageProducer.class);
	final Message message = mock(Message.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);
	given(session.createProducer(dest)).willReturn(producer);
	given(session.getTransacted()).willReturn(true);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	JmsTemplate jt = new JmsTemplate(cf);
	jt.send(dest, sess -> message);
	tm.commit(ts);

	verify(producer).send(message);
	verify(session).commit();
	verify(producer).close();
	verify(session).close();
	verify(con).close();
}
 
Example 20
Source Project: galeb   Source File: ScheduledProducer.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public ScheduledProducer(TargetRepository targetRepository, EnvironmentRepository environmentRepository, JmsTemplate template, HealthService healthService) {
    this.targetRepository = targetRepository;
    this.environmentRepository = environmentRepository;
    this.template = template;
    this.healthService = healthService;
}
 
Example 21
@Bean
public JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) {
    JmsTemplate template = new JmsTemplate(connectionFactory);

    template.setPubSubDomain(false);

    return template;
}
 
Example 22
@Bean
public JmsTemplate jmsTemplate() {
	CachingConnectionFactory ccf = new CachingConnectionFactory(connectionFactory);
	JmsTemplate jmst = new JmsTemplate(ccf);
	jmst.setPubSubDomain(true);	// This sample is publishing to topics
	return jmst;
}
 
Example 23
Source Project: spring-jms   Source File: SenderConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public JmsTemplate orderJmsTemplate() {
  JmsTemplate jmsTemplate =
      new JmsTemplate(cachingConnectionFactory());
  jmsTemplate.setDefaultDestination(orderDestination());
  jmsTemplate.setReceiveTimeout(5000);

  return jmsTemplate;
}
 
Example 24
@Bean
public JmsTemplate producerJmsTemplate() {
	JmsTemplate jt = new JmsTemplate(cachingConnectionFactory());
	jt.setDeliveryPersistent(true);
	jt.setDestinationResolver(producerJndiDestinationResolver());
	jt.setPubSubDomain(true);	// This sample is publishing to topics
	return jt;
}
 
Example 25
Source Project: solace-integration-guides   Source File: PublishJMSTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void validateSuccessfulPublishAndTransferToSuccessWithELOverJNDI() throws Exception {
    ActiveMQConnectionFactory cf = (ActiveMQConnectionFactory) CommonTest.buildJmsJndiConnectionFactory();

    final String destinationNameExpression = "${foo}Queue";
    final String destinationName = "fooQueue";
    PublishJMS pubProc = new PublishJMS();
    TestRunner runner = TestRunners.newTestRunner(pubProc);
    JMSConnectionFactoryProviderDefinition cs = mock(JMSConnectionFactoryProviderDefinition.class);
    when(cs.getIdentifier()).thenReturn("cfProvider");
    when(cs.getConnectionFactory()).thenReturn(cf);

    runner.addControllerService("cfProvider", cs);
    runner.enableControllerService(cs);

    runner.setProperty(PublishJMS.CF_SERVICE, "cfProvider");
    runner.setProperty(PublishJMS.DESTINATION, destinationNameExpression);

    Map<String, String> attributes = new HashMap<>();
    attributes.put("foo", "foo");
    attributes.put(JmsHeaders.REPLY_TO, "cooQueue");
    runner.enqueue("Hey dude!".getBytes(), attributes);
    runner.run(1, false);

    final MockFlowFile successFF = runner.getFlowFilesForRelationship(PublishJMS.REL_SUCCESS).get(0);
    assertNotNull(successFF);

    JmsTemplate jmst = new JmsTemplate(cf);
    BytesMessage message = (BytesMessage) jmst.receive(destinationName);

    byte[] messageBytes = MessageBodyToBytesConverter.toBytes(message);
    assertEquals("Hey dude!", new String(messageBytes));
    assertEquals("cooQueue", ((Queue) message.getJMSReplyTo()).getQueueName());
    assertEquals("foo", message.getStringProperty("foo"));
}
 
Example 26
Source Project: spring-jms   Source File: SenderConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public JmsTemplate orderJmsTemplate() {
  JmsTemplate jmsTemplate =
      new JmsTemplate(cachingConnectionFactory());
  jmsTemplate.setDefaultDestinationName(orderDestination);

  return jmsTemplate;
}
 
Example 27
Source Project: oneops   Source File: SensorPublisher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Close connection.
 */
public void closeConnection() {
    for (JmsTemplate jt : producers) {
        ((PooledConnectionFactory) jt.getConnectionFactory()).stop();
    }
    producers = null;
}
 
Example 28
Source Project: zheng   Source File: JmsUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 延迟发送对象消息
 * @param jmsTemplate
 * @param destination
 * @param objectMessage
 * @param delay
 */
public static void sendMessageDelay(JmsTemplate jmsTemplate, Destination destination, final Serializable objectMessage, final long delay) {
    jmsTemplate.send(destination, new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            ObjectMessage om = session.createObjectMessage(objectMessage);
            om.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
            om.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 1 * 1000);
            om.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, 1);
            return om;
        }
    });
}
 
Example 29
Source Project: blog-sample   Source File: MQProducer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 延时发送
 * @param message 内容,一般为JSON
 * @param time 时间(单位:ms)
 * @author jitwxs
 * @since 2018/5/8 21:08
 */
public void delaySend(Destination destination,String message, Long time) {
    // 得到jmsTemplate
    JmsTemplate jmsTemplate = jmsMessagingTemplate.getJmsTemplate();
    // 发送消息
    jmsTemplate.send(destination, session -> {
        TextMessage textMessage = session.createTextMessage(message);
        // 设置延时时间【关键】
        textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
        return textMessage;
    });
}
 
Example 30
Source Project: blog-sample   Source File: TestProducer.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testProducer() {
    // 1、加载Spring容器
    ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext-activemq.xml");
    // 2、获取jmsTemplate对象
    JmsTemplate jmsTemplate = ac.getBean(JmsTemplate.class);
    // 3、获取Destination对象(以Queue模式为例,如果要测试Topic更换下面注释即可)
    Destination destination = (Destination)ac.getBean("queueDestination");
    //Destination destination = (Destination)ac.getBean("topicDestination");
    // 4、发送消息
    jmsTemplate.send(destination, session -> session.createTextMessage("这是Spring与ActiveMQ整合的测试消息"));
}