实践ActiveMQ之生产者

原生

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection conn = null;
Session session = null;
try {
    conn = cf.createConnection();
    session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = new ActiveMQQueue("queue001");
    MessageProducer producer = session.createProducer(destination);
    TextMessage message = session.createTextMessage();
    message.setText("error");
    producer.send(message);
} catch (JMSException e) {
    logger.error(e.getMessage(), e);
} finally {
	try {
		if (session != null) {
			session.close();
		}
		if (conn != null) {
			conn.close();
		}
	} catch (JMSException ex) {
		logger.error(ex.getMessage(), ex);
	}
}

Spring JMS

1
2
3
4
5
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
	<!-- 推荐使用CachingConnectionFactory -->
	<constructor-arg name="connectionFactory" ref="jmsConnectionFactory" />
	<property name="defaultDestinationName" value="queue001" />
</bean>
1
2
3
4
5
6
jmsTemplate.send(new MessageCreator() {
	public Message createMessage(Session session) throws JMSException {
		TextMessage textMessage = session.createTextMessage(message);
		return textMessage;
	}
});