Speng4整合ActiveMq

首先下载activeMq。下载路径:http://activemq.apache.org/download.html

点进去后,选择自己想要的版本。

这里要注意!activeMq版本5.0以上的要用jdk1.8,我下载的是版本4。

下载后解压,到解压目录..\apache-activemq-5.14.5-bin\apache-activemq-5.14.5\bin\win64下运行activemq.bat,就启动了mq。

启动后可以登陆http://localhost:8161/admin/queues.jsp查看mq 的页面

现在开始配置

导包:

    <!--activeMQ队列-->
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-all</artifactId>
      <version>5.14.5</version>
    </dependency>

配置文件:

activemq-configxml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
    http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">

    <!-- 配置能够产生connection的connectionfactory,由JMS对应的服务厂商提供 -->
    <bean id="tagertConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <constructor-arg name="brokerURL" value="${nulidexiaoma.mq.url}"/>
    </bean>
    <!-- 配置spring管理真正connectionfactory的connectionfactory,相当于spring对connectionfactory的一层封装 -->
    <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
        <property name="targetConnectionFactory" ref="tagertConnectionFactory"/>
    </bean>
    <!-- Spring使用JMS工具类,可以用来发送和接收消息 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <!-- 这里是配置的spring用来管理connectionfactory的connectionfactory -->
        <property name="connectionFactory" ref="connectionFactory"/>
    </bean>
    <!-- 配置destination -->
    <!-- 队列目的地 -->
    <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="spring-queue"/>
    </bean>
    <!-- 话题目的地 -->
    <bean id="itemAddTopic" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg value="item-add-topic"/>
    </bean>
    <!-- MQ 连接池  -->
    <bean id="mqConnectionPoolFactory" class="org.apache.activemq.pool.PooledConnectionFactory"
          destroy-method="stop">
        <property name="connectionFactory" ref="tagertConnectionFactory"/>
    </bean>
    <!-- 线程池 -->
    <bean id="myRegisterMessageExecutor"
          class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <property name="corePoolSize" value="${nulidexiaoma.threadPool.corePoolSize}"/>
        <property name="maxPoolSize" value="${nulidexiaoma.threadPool.maxPoolSize}"/>
        <property name="daemon" value="true"/>
        <property name="keepAliveSeconds" value="120"/>
    </bean>
    <!-- MQ重试策略 -->
    <bean id="wmsRedeliveryPolicy" class="org.apache.activemq.RedeliveryPolicy">
        <property name="maximumRedeliveries" value="${nulidexiaoma.mq.retry}"/>
        <property name="maximumRedeliveryDelay" value="3000"/>
    </bean>
    <!--队列-->
    <import resource="classpath:mq/activemq-producer.xml"/>
    <import resource="classpath:mq/activemq-consumer.xml"/>

</beans>

mq参数文件:

mq.properties

nulidexiaoma.mq.url=tcp://127.0.0.1:61616
nulidexiaoma.mq.retry=2
nulidexiaoma.mq.autoStart=true
nulidexiaoma.threadPool.corePoolSize=100
nulidexiaoma.threadPool.maxPoolSize=200

#队列名
nulidexioama.mq.test.queue = TEST_QUEUE

nulidexiaoma.grn.to.middle.queue.concurrentConsumers=1
nulidexiaoma.grn.to.middle.queue.maxConcurrentConsumers=1

消费队列配置

activemq-consumer.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="testMqConsumer" class="cn.wzl.nulidexiaoma.service.impl.consumer.TestMqConsumer"/>
    <bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="tagertConnectionFactory"/>//配置的工厂
        <property name="destination" ref="testQueue"/>//配置的消息提供者bean 的id
        <property name="messageListener" ref="testMqConsumer"/>//上一个bean 的id
        <property name="taskExecutor" ref="myRegisterMessageExecutor"/>
        <property name="sessionTransacted" value="true"/>
        <property name="concurrentConsumers" value="${nulidexiaoma.grn.to.middle.queue.concurrentConsumers}"/>
        <property name="maxConcurrentConsumers" value="${nulidexiaoma.grn.to.middle.queue.maxConcurrentConsumers}"/>
        <property name="autoStartup" value="${nulidexiaoma.mq.autoStart}"/>
    </bean>
</beans>

提供队列配置

activemq-producer.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!--测试队列 -->
    <bean id="testQueue" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="${nulidexioama.mq.test.queue}"/>
    </bean>
</beans>

在spring配置文件中加载activemq-config.xml和mq.properties

<import resource="classpath:mq/activemq-config.xml"/>
<value>classpath:properties/mq.properties</value>
现在来写工具类
public class MqUtils {
    /**
     * 创建队列消息
     */
    public static MessageCreator createMsg(final Object o){
        if (null == o) return null;
        return new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                String str;
                if(o instanceof String){
                    str = o.toString();
                }else {
                    str = JSON.toJSONString(o);
                }
                return session.createTextMessage(str);
            }
        };
    }

    /**
     * 根据队列名称发送信息
     */
    public static  void sendMsg(final String destination, final Object msg, JmsTemplate jmsTemplate){
        if (null == msg || null == destination) throw new RuntimeException("destination or msg is null");
        MessageCreator mc = createMsg(msg);
        jmsTemplate.send(new ActiveMQQueue(destination),mc);
    }
}
接口:
public interface MqService {
    MessageInfo sendTestMq(String mqStr);
}
实现类:
@Service("mqService")
public class MqServiceImpl implements MqService {
    private static final Logger logger = LoggerFactory.getLogger(MqServiceImpl.class);
    @Resource(name = "testQueue")
    private Destination testQueue;//我们配置的队列信息
    @Resource(name = "jmsTemplate")
    private JmsTemplate jmsTemplate;//配置文件配置的bean
    @Override
    public MessageInfo sendTestMq(String mqStr) {
        MessageInfo messageInfo = new MessageInfo();
        try {
            MessageCreator mqMsg = MqUtils.createMsg(mqStr);
            jmsTemplate.send(testQueue,mqMsg);
            logger.error("推入TEXT_MQ成功:");
        } catch (Exception e) {
            logger.error("推入testQueue出错:"+e.getMessage());
            messageInfo.setMessageStatus(MessageStatus.ERROR.getStatus(),"推入testQueue出错:"+e.getMessage());
        }
        return messageInfo;
    }
}
消费类:
public class TestMqConsumer implements MessageListener {
    private static final Logger logger = LoggerFactory.getLogger(TestMqConsumer.class);
    @Override
    public void onMessage(Message message) {
        TextMessage msg = (TextMessage) message;
        try {
            String text = msg.getText();
            logger.error("测试队列消费者消费TEXT_MQ成功,内容为:" + text);
        } catch (JMSException e) {
            e.printStackTrace();
            logger.error("测试队列消费TEXT_MQ失败:" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("测试队列消费TEXT_MQ失败:" + e.getMessage());
        }
    }
}

消费者类要实现MessageListener接口,重写onMessage方法。

测试:

@Test
    public void sendToMq(){
        try {
            MessageInfo messageInfo = new MessageInfo();
            mqService.sendTestMq("123");
            System.out.println("ok");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
当我们往队列推入消息时,mq会自动去消费,即调用我们写的TestMqConsumer类中的onMessage方法,消费我们推入的信息。


















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值