ActiveMQ进阶(一)ActiveMQ与Spring的整合

前言

      本章学习使用Spring整合ActiveMQ

方法

1.概念

我们知道,在实际的项目开发中,通常是结合框架的,例如结合我们熟悉的Spring。

那ActiveMQ也是如此,我们的spring提供了对ActiveMQ的相关支持。

2.准备工作

我们需要准备一系列的jar包,推荐使用maven:

本次讲解需要用到如下的jar包,请进行如下的配置:

3.编写Spring配置文件

我们配置spring的全局配置文件applicationContext.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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 配置组件扫描,以便于告诉Spring哪里有注解 -->
    <context:component-scan base-package="cn.edu.ccut"></context:component-scan>
    <!-- 配置ActiveMQ的工厂,由于安全认证的原因需要配置三个参数,这里要注意用户名和密码的属性值写法很讲究 -->
    <bean id="factory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://192.168.1.103:61616" />
        <property name="userName" value="admin" />
        <property name="password" value="admin" />
    </bean>
    <!-- 配置ActiveMQ的连接池 -->
    <bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory"
          destroy-method="stop">
        <property name="connectionFactory" ref="factory"/>
        <property name="maxConnections" value="100"/>
    </bean>
    <!-- 配置缓存 -->
    <bean id="cachingConnectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
        <property name="targetConnectionFactory" ref="jmsFactory"/>
        <property name="sessionCacheSize" value="1"/>
    </bean>
    <!-- 配置最为重要的模板类,后面的代码开发需要使用该类 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="cachingConnectionFactory"/>
        <property name="messageConverter">
            <bean class="org.springframework.jms.support.converter.SimpleMessageConverter"/>
        </property>
    </bean>
    
    <!--测试Queue,队列的名字是spring-queue-->
    <bean id="destinationQueue" class="org.apache.activemq.command.ActiveMQQueue">
        <!--<constructor-arg index="0" value="spring-queue"/>-->
        <constructor-arg name="name" value="spring-queue"/>
    </bean>
    
    <!--测试Topic-->
    <!-- <bean id="destinationTopic" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg index="0" value="spring-topic"/>
    </bean> -->
    
    <!-- 配置jms容器,用于监听生产者发送的消息 -->
    <bean id="jmsContainer"
          class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="cachingConnectionFactory"/>
        <property name="destination" ref="destinationQueue"/>
        <property name="messageListener" ref="messageListener"/>
    </bean>

    <!--消息监听器-->
    <bean id="messageListener" class="cn.edu.ccut.test.MyMessageListener">
    </bean>

</beans>

4.编写生产者代码

package cn.edu.ccut.test;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class SpringTest {

	@Resource(name = "jmsTemplate")
    private JmsTemplate jmsTemplate;

    @Resource(name = "destinationQueue")
    private Destination destination;

	@Test
	public void testActiveMQ(){
		//通常消息都是JSON串,由项目的实际对象转化而来
		String msg = "spring-activeMQ";
		try {
            jmsTemplate.send(destination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    return session.createTextMessage(msg);
                }
            });

        } catch (Exception ex) {
            ex.printStackTrace();
        }
	}
}

5.编写消费者监听器

package cn.edu.ccut.test;

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

public class MyMessageListener implements MessageListener {

    @Override
    public void onMessage(Message msg) {
        if (msg instanceof TextMessage) {
            try {
                TextMessage txtMsg = (TextMessage) msg;
                String message = txtMsg.getText();
                //实际项目中拿到String类型的message(通常是JSON字符串)之后,
                //会进行反序列化成对象,做进一步的处理
                System.out.println("receive txt msg===" + message);
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
        } else {
            throw new IllegalArgumentException("Message must be of type TextMessage");
        }
    }
}

6.执行生产者代码观察效果

执行生产者代码发送消息,由于监听器的原因,消费者会立刻收到消息的内容:

图片显示我发送了三次消息:

 

PTP模式即使如此,那么Topic也是一样多的,请大家自己去尝试使用!! 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值