ActiveMQ的安装与调用样例

因为ActiveMQ是运行在jetty服务器上的,需要先安装jdk,因为我选的是最新的AQ,所以安装了比较新的jdk1.8

jdk安装省略...

和大多数软件类似,先官网下载

wget -c -r https://mirrors.tuna.tsinghua.edu.cn/apache//activemq/5.15.5/apache-activemq-5.15.5-bin.tar.gz

之后解压:

tar -zvxf activemq-xxx.tar.gz

解压之后就可以直接运行了, ./activemq start

查看是否运行正常:

netstat -tlnp | grep 8161

查看是否有8161端口服务进程。

二、调用ActiveMQ样例

消息生产者Producer.java:

public static void main(String[] args) throws Exception { 
		Connection connection = null;
		Session session = null;
		try {
			// 创建链接工厂
			ConnectionFactory factory = new ActiveMQConnectionFactory("admin",
					"admin","tcp://192.168.48.10:61616");
			// 通过工厂创建一个连接
			connection = factory.createConnection();
			// 启动连接
			connection.start();
			// 创建一个session会话
			session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			// 创建一个消息队列
			Destination destination = session.createQueue("mq.test");
			// 创建消息制作者
			MessageProducer producer = session.createProducer(destination);
			// 设置持久化模式
			producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
			sendMessage(session, producer);
			// 提交会话
			session.commit();
		} catch (Exception e) {
			throw e;
		} finally {
			// 关闭释放资源
			if (session != null) {
				session.close();
			}
			if (connection != null) {
				connection.close();
			}
		}
	}

消息消费者Comsumer.java

public static void main(String[] args) throws Exception {
		Connection connection = null;
		Session session = null;
		try {
			// 创建链接工厂
			ConnectionFactory factory = new ActiveMQConnectionFactory("admin",
					"admin", "tcp://192.168.48.10:61616");
			// 通过工厂创建一个连接
			connection = factory.createConnection();
			// 启动连接
			connection.start();
			// 创建一个session会话
			session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			// 创建一个消息队列
			Destination destination = session.createQueue("mq.test");
			// 创建消息制作者
			MessageConsumer consumer = session.createConsumer(destination);
			while (true) {
				// 接收数据的时间(等待) 100 ms
				Message message = consumer.receive(1000 * 100);
				TextMessage text = (TextMessage) message;
				if (text != null) {
					System.out.println("接收:" + text.getText());
				} else {
					break;
				}
			}
			// 提交会话
			session.commit();
		} catch (Exception e) {
			throw e;
		} finally {
			// 关闭释放资源
			if (session != null) {
				session.close();
			}
			if (connection != null) {
				connection.close();
			}
		}
	}

查看消息发送接收状态:

三、与spring整合

消息生产者:

springcontext.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:context="http://www.springframework.org/schema/context"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-4.3.xsd"
	   default-autowire="byName" default-lazy-init="false">
	
	<!-- 采用注释的方式配置bean -->
	<context:annotation-config />

	<!-- 配置要扫描的包 -->
	<context:component-scan base-package="cn.javaxxw" />

	<!-- 读入配置属性文件 -->
	<context:property-placeholder location="classpath:config/mq.properties" />

	<!-- proxy-target-class默认"false",更改为"ture"使用CGLib动态代理 -->
	<aop:aspectj-autoproxy proxy-target-class="true" />	
	<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <!-- ActiveMQ服务地址 -->
        <property name="brokerURL" value="${mq.brokerURL}" />
        <property name="userName" value="${mq.userName}"></property>
        <property name="password" value="${mq.password}"></property>
    </bean>


    <bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
        <property name="connectionFactory" ref="targetConnectionFactory" />
        <property name="maxConnections" value="${mq.pool.maxConnections}" />
    </bean>

    <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
    <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
        <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
        <property name="targetConnectionFactory" ref="pooledConnectionFactory" />
    </bean>


    <!-- 队列模板 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
        <property name="connectionFactory" ref="connectionFactory"/>
        <property name="defaultDestinationName" value="${queueName}"></property>
    </bean>
</beans>

消息生产者:

@Service("mqProducer")
public class MQProducer {

    @Autowired
    private JmsTemplate jmsTemplate;
    /**
     * 发送消息.
     * @param order
     */
    public void sendMessage(final String message) {

        //发送消息到MQ
        jmsTemplate.send(new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(message);
            }
        });
    }
}

测试样例:

public static void main(String[] args)  {
        try {
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-context.xml");
            context.start();

            MQProducer mqProducer = (MQProducer) context.getBean("mqProducer");
            // 邮件发送 
            mqProducer.sendMessage("测试消息发送");
            Thread.sleep(100);
            context.stop();
        } catch (Exception e) {
            logger.error("MQProducer context start error:", e);
            System.exit(0);
        } finally {
            logger.info("System.exit");
            System.exit(0);
        }
    }

消息消费者监听springContext.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:context="http://www.springframework.org/schema/context"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
           http://www.springframework.org/schema/aop   
           http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-4.3.xsd"
	default-autowire="byName" default-lazy-init="false">
	
	<!-- 采用注释的方式配置bean -->
	<context:annotation-config />

	<!-- 配置要扫描的包 -->
	<context:component-scan base-package="cn.javaxxw" />

	<!-- 读入配置属性文件 -->
	<context:property-placeholder location="classpath:config/mq.properties" />

	<!-- proxy-target-class默认"false",更改为"ture"使用CGLib动态代理 -->
	<aop:aspectj-autoproxy proxy-target-class="true" />	
	
	<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <!-- ActiveMQ服务地址 -->
        <property name="brokerURL" value="${mq.brokerURL}" />
        <property name="userName" value="${mq.userName}"></property>
        <property name="password" value="${mq.password}"></property>
    </bean>


    <bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
        <property name="connectionFactory" ref="targetConnectionFactory" />
        <property name="maxConnections" value="${mq.pool.maxConnections}" />
    </bean>

    <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
    <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
        <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
        <property name="targetConnectionFactory" ref="pooledConnectionFactory" />
    </bean>


    <!-- 队列模板 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
        <property name="connectionFactory" ref="connectionFactory"/>
        <property name="defaultDestinationName" value="${queueName}"></property>
    </bean>

    <!--这个是队列目的地-->
    <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg>
            <value>${queueName}</value>
        </constructor-arg>
    </bean>
    <!-- 消息监听器 -->
    <bean id="defaultMessageQueueListener" class="cn.javaxxw.listener.DefaultMessageQueueListener"/>
    <!-- 消息监听容器 -->
    <bean id="jmsContainer"
          class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destination" ref="queueDestination" />
        <property name="messageListener" ref="defaultMessageQueueListener" />
    </bean>
</beans>

消息监听器配置MessageListener.java:

  private static final Log logger = LogFactory.getLog(DefaultMessageQueueListener.class);


    @Override
    public void onMessage(Message message) {

        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            try {
                final String ms = textMessage.getText();
                 logger.info("接收到消息"+ms);

                 //TODO 接收到消息后这里进行业务处理
            }catch (Exception e){
                logger.error("have a error");
            }

        }
    }

测试样例:

 public static void main(String[] args) {
        try {
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-context.xml");
            context.start();
        } catch (Exception e) {
            logger.error("==>MQ context start error:", e);
            System.exit(0);
        }
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值