[size=x-large]项目中因为要监听IBM MQ 队列的消息,想到用Spring JMS来做[/size]
[b]Spring JMS介绍[/b]
Spring对JMS(Java Message Service)的封装,简化了代码量,便于使用 :wink:
[b]下面直接贴代码来说明[/b]
[*]定义MQ连接工厂
[*]定义工厂适配器
[*]队列定义
[*]队列监听容器
[*]消息监听
[b]Spring JMS介绍[/b]
Spring对JMS(Java Message Service)的封装,简化了代码量,便于使用 :wink:
[b]下面直接贴代码来说明[/b]
[*]定义MQ连接工厂
<bean id="testFeMQQueueConnectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
<property name="hostName" value="${HOSTNAME}" />
<property name="port" value="${PORT}" />
<property name="queueManager" value="${MQMANAGERNAME}" />
<property name="channel" value="${CHANNEL}" />
<property name="CCSID" value="${CCSID}" />
<property name="transportType" value="1" />
</bean>
[*]定义工厂适配器
<bean id="testUserCredentialsConnectionFactoryAdapter"
class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
<property name="targetConnectionFactory" ref="testMQQueueConnectionFactory" />
</bean>
[*]队列定义
<bean id="testMQQueue" class="com.ibm.mq.jms.MQQueue">
<constructor-arg name="queueManagerName" value="${MQMANAGERNAME}" />
<constructor-arg name="queueName" value="${MQ_QUEUE_NAME}" />
</bean>
[*]队列监听容器
<bean id="testListenserContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer"
lazy-init="false">
<property name="connectionFactory"
ref="testUserCredentialsConnectionFactoryAdapter" />
<property name="destination" ref="testMQQueue" />
<property name="messageListener" ref="testMessageListener" />
<property name="sessionTransacted" value="false" />
<!-- 设置固定的线程数 -->
<property name="concurrentConsumers" value="10"></property>
</bean>
[*]消息监听
package com.liyghting.mq.listener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class TestMessageListener implements MessageListener {
private static final Logger logger = LoggerFactory.getLogger(TestMessageListener .class);
@Override
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage)message;
try {
String msg = textMessage.getText();
logger.info("消息[{}]",msg);
} catch (JMSException e) {
logger.error("消息监听异常", e);
}
}
}