Spring整合ActiveMQ

Easter79
• 阅读 544

前面介绍了ActiveMQ的基本安装使用,并写了简单的生产者、消费者。下面主要介绍ActiveMQ的消费者的Listener、Spring整合ActiveMQ。

一、消费者Listener

  之前创建的消费者,接收消息的时候都是直接使用consumer.receive(),每次消费一条数据,启动一次获取一次,十分的木讷。实际开发工作中,基本不会使用此种方式,一般,消息的消费者都是持续监听目标队列Queue或者主题Topic,主要应用程序不主动关闭,会一直监听消费消息数据。

  JMS listener的消费者:

package com.cfang.mq.simpleCase;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class ConsumerListener {

    public static void main(String[] args) {
        ConsumerListener consumerListener = new ConsumerListener();
        consumerListener.listenMessage();
    }
    
    public void listenMessage() {
        ConnectionFactory factory = null;
        Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageConsumer consumer = null;
        try {
            factory = new ActiveMQConnectionFactory("admin", "admin", "tcp://172.31.31.160:61616");
            connection = factory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue("tp_simple_queue");
            consumer = session.createConsumer(destination);
            consumer.setMessageListener(new MessageListener() {
                public void onMessage(Message message) {
                    try {
                        TextMessage textMessage = (TextMessage) message;
                        System.out.println(textMessage.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });
            //阻塞代码,模拟应用程序不关闭。如果关闭了,那监听也自动停止了
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(consumer != null){
                try {
                    consumer.close();
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(session != null){
                try {
                    session.close();
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(connection != null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

二、Spring整合

  Spring整合ActiveMQ非常的便捷,Spring提供了JmsTemplate对其进行操作,非常的方便,下面从配置文件到程序代码逐步介绍。

  1、Spring-jms配置文件

<?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:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:amq="http://activemq.apache.org/schema/core"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

    <context:component-scan base-package="com.cfang.amq">
        
    </context:component-scan>
        
    <!-- 配置ActiveMQConnectionFactory连接工厂对象 -->
    <amq:connectionFactory id="amqConnectionFactory" brokerURL="tcp://172.31.31.160:61616" userName="admin" password="admin"/>
    <!-- 配置connectionFactory的连接池信息 -->
    <bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
        <property name="connectionFactory" ref="amqConnectionFactory"></property>
        <property name="maxConnections" value="10"></property>
    </bean>
    <!-- 带有缓存功能的连接工厂,Session缓存大小可配置 -->
    <bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
        <property name="targetConnectionFactory" ref="pooledConnectionFactory"></property>
        <property name="sessionCacheSize" value="100"></property>
    </bean>
    <!-- 配置JmsTemplate -->
    <bean id="template" class="org.springframework.jms.core.JmsTemplate">
        <!-- 给定连接工厂, 必须是spring创建的连接工厂. -->
        <property name="connectionFactory" ref="connectionFactory"></property>
        <!-- 可选 - 默认目的地命名 -->
        <property name="defaultDestinationName" value="tp_simple_queue"></property>
    </bean>
    <!-- 配置生产者Producer -->
    <bean id="springProducer" class="com.cfang.amq.SpringProducer"/>
    
    <!-- 配置消费listener -->
    <bean  class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory"></property>
        <property name="destinationName" value="tp_simple_queue"/>
        <property name="messageListener" ref="springConsumer"></property>
        <property name="concurrentConsumers" value="1"/> 
    </bean>
    <!-- 消费者 -->
    <bean id="springConsumer" class="com.cfang.amq.SpringConsumer"/>
</beans>

  2、单元测试

package com.cfang.prebo.activemq;

import java.io.IOException;
import java.util.Scanner;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.cfang.amq.SpringProducer;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext-jms.xml" })
public class SpringListenerTest {
    
    @Autowired
    private SpringProducer springConsumer;

    @Test
    public void start() throws Exception {
        System.out.println("======start");
        
        //发送消息
        Scanner scanner = new Scanner(System.in);
        while(true) {
            System.out.print("producer send msg : ");
            String line = scanner.nextLine();
            if("exit".equals(line)) {
                break;
            }
            springConsumer.sendMsg(null, line);
        }
        
        //阻塞
//        System.in.read();
    }
    
}

  3、运行结果:

  Spring整合ActiveMQ

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
activemq 使用介绍
1,activemq分为queue和topic两种2,下面先介绍queue,使用spring集成build.gradlecompile"org.springframework:springjms:3.2.1.RELEASE"compile"org.apache.activemq:activemqcore
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
ActiveMQ消息队列详解
activemq消息队列,分为生产者和消费者。.1创建生产者publicclassProducter{//ActiveMq的默认用户名privatestaticfinalStringUSERNAMEActiveMQConnection.DEFAULT\_USER;//ActiveMq的默认登录密码pr
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k