欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring JMS与IBM MQ 整合,监听

程序员文章站 2022-07-13 14:34:57
...
项目中因为要监听IBM MQ 队列的消息,想到用Spring JMS来做

Spring JMS介绍
Spring对JMS(Java Message Service)的封装,简化了代码量,便于使用Spring JMS与IBM MQ 整合,监听
            
    
    博客分类: Java springjmsjava 

下面直接贴代码来说明
  • 定义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);
    		}
    	}
    }
    
    相关标签: spring jms java