1. JndiTemplate
2. ConnectionFactory
3. Destination
4. JmsTemplate
5. Spring JMS消息发送
6. Spring JMS消息接受
1. JndiTemplate
<!-- JndiTemplate -->
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">
weblogic.jndi.WLInitialContextFactory
</prop>
<prop key="java.naming.provider.url">
t3://localhost:7001
</prop>
</props>
</property>
</bean>
2. ConnectionFactory
<!-- ConnectionFactory -->
<bean id="connectionFactory"
class="org.springframework.jndi.JndiObjectFactoryBean"
p:jndiTemplate-ref="jndiTemplate"
p:jndiName="weblogic.jms.ConnectionFactory" />
3. Destination
<!-- Destination -->
<bean id="destination"
class="org.springframework.jndi.JndiObjectFactoryBean"
p:jndiTemplate-ref="jndiTemplate"
p:jndiName="txazoQueue" />
4. JmsTemplate
<!-- JmsTemplate -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"
p:connectionFactory-ref="connectionFactory"
p:defaultDestination-ref="destination"
p:receiveTimeout="20000" />
5. Spring JMS消息发送
<!-- JmsSender -->
<bean id="jmsSender" class="com.txazo.jms.JmsSender"
p:jmsTemplate-ref="jmsTemplate" />
public class JmsSender {
private JmsTemplate jmsTemplate;
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void sendMesage() {
jmsTemplate.send(new MessageCreator() {
@Override
public Message createMessage(Session session)
throws JMSException {
return session
.createTextMessage("This is a spring jms message");
}
});
}
}
jmsSender.sendMesage();
6. Spring JMS消息接受
<!-- JmsReceiver -->
<bean id="jmsReceiver" class="com.txazo.jms.JmsReceiver" />
<!-- ListenerContainer -->
<bean id="listenerContainer"
class="org.springframework.jms.listener.
DefaultMessageListenerContainer"
p:connectionFactory-ref="connectionFactory"
p:destination-ref="destination"
p:messageListener-ref="jmsReceiver" />
public class JmsReceiver implements MessageListener {
@Override
public void onMessage(Message message) {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println(textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
public class JmsReceiver implements SessionAwareMessageListener {
@Override
public void onMessage(Message message, Session session) {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println(textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}