首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring 整合 ActiveMQ 實戰:JMS 消息收發完整指南

     編輯:Java 相關知識

本文通過一個完整的 Web 項目示例,詳細演示如何使用 Spring 整合 ActiveMQ 實現 JMS(Java Message Service)消息的發送與接收,重點講解核心配置與代碼結構,適合初學者快速上手。

環境準備

  1. 下載 ActiveMQ(官網),解壓後運行 bin/activemq.bat 啟動 Broker,默認端口 61616。
  2. 創建 Web 項目(如 MyEclipse),導入核心 JAR:spring.jar、apache-activemq.jar、commons-pool.jar、log4j.jar、commons-logging.jar。建議避免使用 IDE 自帶舊版 Spring 包。

Spring 配置文件

發送端配置 (jms_sender.xml)

<bean id="connectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
  <property name="connectionFactory">
    <bean class="org.apache.activemq.ActiveMQConnectionFactory">
      <property name="brokerURL" value="tcp://localhost:61616"/>
    </bean>
  </property>
</bean>
<bean id="dest" class="org.apache.activemq.command.ActiveMQQueue">
  <constructor-arg value="myDest"/>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
  <property name="connectionFactory" ref="connectionFactory"/>
  <property name="defaultDestination" ref="dest"/>
</bean>
<bean id="messageSender" class="com.bo.impl.MessageSender">
  <property name="jmsTemplate" ref="jmsTemplate"/>
</bean>

接收端配置 (jms_receiver.xml)

結構類似,僅將 messageSender 替換為 messageReceiver,指向 com.bo.impl.MessageReceiver。

核心業務類

消息發送器

public class MessageSender extends JmsGatewaySupport {
    public void sendTextMsg(final String msg) {
        getJmsTemplate().send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                TextMessage message = session.createTextMessage(msg);
                message.setStringProperty("JMSXUserID", "123456789");
                message.setStringProperty("JMSXApp1ID", "001002");
                return message;
            }
        });
    }
}

消息接收器

public class MessageReceiver extends JmsGatewaySupport {
    public void receiverTextMsg() {
        TextMessage textMsg = (TextMessage) getJmsTemplate().receive();
        try {
            // 打印 Header、Properties、Body 完整信息
            System.out.println("消息編碼:" + textMsg.getJMSMessageID());
            System.out.println("目標對象:" + textMsg.getJMSDestination());
            System.out.println("消息模式:" + textMsg.getJMSDeliveryMode()); // 2=持久
            System.out.println("發送時間:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(textMsg.getJMSTimestamp())));
            System.out.println("失效時間:" + textMsg.getJMSExpiration()); // 0=永不過期
            System.out.println("優先級:" + textMsg.getJMSPriority()); // 0-9
            System.out.println("關聯編碼:" + textMsg.getJMSCorrelationID());
            System.out.println("回復地址:" + textMsg.getJMSReplyTo());
            System.out.println("消息類型:" + textMsg.getJMSType());
            System.out.println("是否重傳:" + textMsg.getJMSRedelivered());
            // Properties
            System.out.println("用戶編碼:" + textMsg.getStringProperty("JMSXUserID"));
            System.out.println("應用編碼:" + textMsg.getStringProperty("JMSXApp1ID"));
            System.out.println("嘗試次數:" + textMsg.getStringProperty("JMSXDeliveryCount"));
            // Body
            System.out.println("消息內容:" + textMsg.getText());
        } catch (Exception e) { e.printStackTrace(); }
    }
}

測試類與運行結果

分別編寫 TestMessageSender、TestMessageReceiver 通過 FileSystemXmlApplicationContext 加載配置並調用業務方法。運行發送端後再運行接收端,控制台輸出完整消息元數據與內容,確認整合成功。

關鍵點總結

  • 使用 PooledConnectionFactory 提升連接性能。
  • JmsTemplate 封裝底層 JMS API,簡化發送/接收代碼。
  • 消息屬性(setStringProperty)可攜帶業務擴展信息。
  • 同步接收 receive() 會阻塞,生產環境建議配置消息監聽器容器實現異步消費。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved