Spring 与 ActiveMQ 整合代码

2021-12-08 09:06:48 浏览数 (2)

Spring 与 ActiveMQ 整合代码

代码语言:javascript复制
<bean id="targetConnectionFactory" class="org.apache.activemq.spring.ActiveMQConnectionFactoryFactoryBean">
        <property name="tcpHostAndPorts">
            <list>
                <value>tcp://localhost:61616</value>
            </list>
        </property>
        <property name="maxReconnectDelay" value="5000"/>
    </bean>

    <!-- 配置JMS ConnectionFactory -->
    <bean id="jmsConnectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
        <property name="cacheProducers" value="true"/>
        <property name="targetConnectionFactory" ref="targetConnectionFactory">
        </property>
        <property name="reconnectOnException" value="true"/>
    </bean>


    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="jmsConnectionFactory"/>
    </bean>

    <!-- 主题消息目的地 -->
    <!--<bean class="org.apache.activemq.command.ActiveMQTopic">-->
    <!--&lt;!&ndash; 设置主题的名字&ndash;&gt;-->
    <!--<constructor-arg name="name" value="subject"/>-->
    <!--</bean>-->

    <!--队列消息目的地 -->

    <!--短信队列-->
    <bean id="smsQueue" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg name="name" value="smsQueue"/>
    </bean>
    <!--信鸽推送-->
    <!--发送邮件-->


    <bean id="smsQueueListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="concurrentConsumers" value="10"/>
        <property name="connectionFactory" ref="jmsConnectionFactory"/>
        <property name="destination" ref="smsQueue"/>
        <property name="messageListener" ref="smsQueueConsumer"/>
        <property name="pubSubNoLocal" value="false"/>
        <property name="pubSubDomain" value="false"/>
    </bean>

短信消息处理

代码语言:javascript复制
public class SmsQueueConsumer implements MessageListener {
    @Override
    public void onMessage(Message message) {
        String topicName = null;
        try {
            Queue jmsReplyTo = (Queue) message.getJMSDestination();
            ;
            topicName = jmsReplyTo.getQueueName();
        } catch (JMSException e) {
            e.printStackTrace();
        }

        if (message instanceof TextMessage) {
            try {
                System.out.println(Thread.currentThread().getName()   ",收到队列("   topicName   ")的消息:"   ((TextMessage) message).getText());
            } catch (JMSException ex) {
                throw new RuntimeException(ex);
            }
        } else {
            throw new IllegalArgumentException("Message must be of type TextMessage");
        }
    }
}

0 人点赞