Spring整合activeMQ

   最近項目上一個應用就是處理完業務邏輯後要發短信通知客戶是否處理成功,如果把這個發短信的業務也放到一起處理,可能會導致延遲等問題,所以採用異步處理的方式,把發短信的業務邏輯扔到activeMQ消息中間件中處理。

消息生產者Service:

package com.booth.common.service;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class MsgQueueSenderService {

    private final static Logger logger = LoggerFactory.getLogger(MsgQueueSenderService.class);

    private JmsTemplate jmsTemplate;

    private Destination appAuthDestination;

    @Value("${appAuthQueue.retry}")
    private boolean IS_RETRY;

    @Value("${appAuthQueue.timeout.max}")
    private Long TIMEOUT_MAX;

    @Value("${appAuthQueue.timeout.step}")
    private Long TIMEOUT_STEP;

    public void sendMessage(final Object message) {  
        final JSONObject json = JSONObject.parseObject(JSON.toJSONString(message));
        Long timeout = json.get("timeout") == null? 0L:json.getLong("timeout");
        final Long delay = timeout;
        if (IS_RETRY){
            if (timeout < TIMEOUT_MAX){
                timeout += TIMEOUT_STEP;
            }else{
                timeout = TIMEOUT_MAX;
            }
            json.put("timeout", timeout);
        }else if (!IS_RETRY && timeout > 0){
            return;
        }

        jmsTemplate.send(appAuthDestination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {  
                TextMessage tm = session.createTextMessage();
                tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
                logger.debug("mq send message:"+json.toJSONString());
                tm.setText(json.toJSONString());
                return tm;
            }  
        });  
    }

    public JmsTemplate getJmsTemplate() {
        return jmsTemplate;
    }

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public Destination getAppAuthDestination() {
        return appAuthDestination;
    }

    public void setAppAuthDestination(Destination appAuthDestination) {
        this.appAuthDestination = appAuthDestination;
    } 



}

消息監聽:

package com.booth.common.push;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.booth.common.service.HandleApiService;
import com.booth.common.service.MsgQueueSenderService;

public class PushToServerByMsgQueueListener implements MessageListener{

    @Autowired
    HandleApiService apiService;

    @Autowired
    MsgQueueSenderService msgQueueSenderService;

    @Override
    public void onMessage(Message message) {
        try{
            if (message != null) {
                System.out.println("接收到Task:" + ((TextMessage) message).getText());
            }
            JSONObject json = (JSONObject) JSON.parse(((TextMessage) message).getText());
            boolean rlt = apiService.send(json);
            if (!rlt){
                msgQueueSenderService.sendMessage(json);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}

其中HandleApiService 用於處理發短信的業務邏輯,其處理完返回true或者false,如果沒有處理成功則重新創建任務。

消息消費者:
生產者往指定目的地Destination發送消息後,接下來就是消費者對指定目的地的消息進行消費了。那麼消費者是如何知道有生產者發送消息到指定目的地Destination了呢?每個消費者對應每個目的地都需要有對應的MessageListenerContainer。對於消息監聽容器而言,除了要知道監聽哪個目的地之外,還需要知道到哪裏去監聽,也就是說它還需要知道去監聽哪個JMS服務器,通過配置MessageListenerContainer的時候往裏面注入一個ConnectionFactory來實現的。所以我們在配置一個MessageListenerContainer的時候有三個屬性必須指定:一個是表示從哪裏監聽的ConnectionFactory;一個是表示監聽什麼的Destination;一個是接收到消息以後進行消息處理的MessageListener

相關配置文件:
applicationContext-mq.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:amq="http://activemq.apache.org/schema/core"
    xmlns:jms="http://www.springframework.org/schema/jms"
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd   
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jms
        http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
        http://activemq.apache.org/schema/core
        http://activemq.apache.org/schema/core/activemq-core-5.7.0.xsd">
        <amq:connectionFactory id="amqConnectionFactory"
        brokerURL="tcp://url地址:61616" userName="admin" password="admin" />

    <bean id="connectionFactory"
        class="org.springframework.jms.connection.CachingConnectionFactory">
        <constructor-arg ref="amqConnectionFactory" />
        <property name="sessionCacheSize" value="100" />
    </bean>

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

    <!-- Spring JmsTemplate 的消息生產者 start-->
    <bean id="msgQueueSenderService" class="com.booth.common.service.MsgQueueSenderService">
        <property name="jmsTemplate" ref="jmsTemplate" />
        <property name="appAuthDestination" ref="appAuthDestination" />
    </bean>
<!--Spring JmsTemplate 的消息生產者 end-->

    <!--這個是隊列目的地,點對點的-->  
    <bean id="appAuthDestination" class="org.apache.activemq.command.ActiveMQQueue">  
        <constructor-arg value="${appAuthQueue}">  
        </constructor-arg>  
    </bean>

    <!-- 消息消費者 start-->
    <!-- 消息監聽器 -->  
    <bean id="appAuthListener" class="com.booth.common.push.PushToServerByMsgQueueListener"/>
        <bean id="msgQueueSenderService" class="com.booth.common.service.MsgQueueSenderService">
        <property name="jmsTemplate" ref="jmsTemplate" />
        <property name="appAuthDestination" ref="appAuthDestination" />
    </bean>

    <!-- 消息監聽容器 -->  
    <bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">  
        <property name="connectionFactory" ref="connectionFactory" />  
        <property name="destination" ref="appAuthDestination" />  
        <property name="messageListener" ref="appAuthListener" />  
    </bean>
<!-- 消息消費者 end -->

</beans>

activemq.properties本案例中列舉的涉及到的部分配置

appAuthQueue = appAuthTestQueue
appAuthQueue.retry = true
appAuthQueue.timeout.max = 30000
appAuthQueue.timeout.step = 5000
發佈了48 篇原創文章 · 獲贊 15 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章