前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >Spring JMS的使用

Spring JMS的使用

作者头像
端碗吹水
发布于 2020-09-23 06:22:36
发布于 2020-09-23 06:22:36
89200
代码可运行
举报
运行总次数:0
代码可运行

Spring JMS简介

我们都知道使用Spring可以简化我们的开发,同样的使用Spring也可以集成JMS来连接ActiveMQ,这里说明一下几个需要用到的类:

1.首先是 ConnectionFactory 的实现类,Spring封装了两个连接工厂的实现类。因为JmsTemplate每次发消息都会重新创建连接、会话和productor,所以Spring提供的这两个实现类都是具有连接池的功能的。这两个实现类分别是 SingleConnectionFactory 和 CachingConnectionFactory:

SingleConnectionFactory:对于建立JMS服务器链接的请求只会一直返回同一个Connection,并且会忽略Connection的close方法调用。(org.springframework.jms.connection.SingleConnectionFactory) CachingConnectionFactory:继承了SingleConnectionFactory,所以它拥有SingleConnectionFactory的所有功能,同时它还新增了缓存功能,它可以缓存Session、MessageProducer和MessageConsumer。(org.springframework.jms.connection.CachingConnectionFactory)

2.JmsTemplate 这是Spring提供的用于发送和接收消息的模板类,只需向Spring容器内注册这个类就可以使用JmsTemplate方便的操作jms,JmsTemplate 类是线程安全的,我们可以在整个应用范围使用。

3.MessageListener 消息监听器,实现一个onMessage方法,该方法只接受一个Message参数,在该方法内对消息进行处理。


Spring JMS的使用_1

创建一个Maven工程,在pom.xml文件中,添加如下依赖:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<properties>
    <spring.version>4.2.5.RELEASE</spring.version>
</properties>
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jms</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-core</artifactId>
        <version>5.7.0</version>
        <exclusions>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

然后创建Spring的配置文件,不同的角色我们希望使用不同的配置文件,但这些配置文件有些配置是一致的,所以我们先创建一个通用的配置文件把可复用的部分抽取出来,内容如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="org.zero01.jms"/>

    <!-- ActiveMQ为我们提供的ConnectionFactory -->
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"
          p:brokerURL="tcp://192.168.190.129:61616"
    />

    <!-- SpringJMS为我们提供的连接池 -->
    <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory"
          p:targetConnectionFactory-ref="targetConnectionFactory"
    />

    <!-- 一个队列的目的地,点对点的 -->
    <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
        <!-- 目的地的名称 -->
        <constructor-arg value="queue"/>
    </bean>
</beans>

然后创建消息生产者的配置文件,内容如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <import resource="common.xml"/>
    <context:component-scan base-package="org.zero01.jms"/>
    <!-- SpringJMS提供的用于发送和接收消息的模板类 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"
        p:connectionFactory-ref="connectionFactory"
    />
</beans>

基本的配置完成之后,我们先来创建消息发送服务。新建一个 ProducerService 接口,代码如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package org.zero01.jms.producer;

public interface ProducerService {
    void sendMessage(String message);
}

新建该接口的实现类,代码如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package org.zero01.jms.producer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.TextMessage;

/**
 * @program: jms-spring
 * @description: 消息发送服务
 * @author: 01
 * @create: 2018-05-27 09:28
 **/
@Service("producerService")
public class ProducerServiceImpl implements ProducerService {

    @Autowired
    private JmsTemplate jmsTemplate;

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

    /**
     * 发送消息
     * @param message
     */
    public void sendMessage(String message) {
        // 使用JmsTemplate来发送消息
        jmsTemplate.send(destination, (session) -> {
            // 创建一个文本类型的消息体
            return session.createTextMessage(message);
        });
        System.out.println("发送消息: " + message);
    }
}

然后新建一个消息生产者,代码如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package org.zero01.jms.producer;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @program: jms-spring
 * @description: 消息生产者
 * @author: 01
 * @create: 2018-05-27 10:11
 **/
public class AppProducer {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        ProducerService producerService = (ProducerService) context.getBean("producerService");
        for (int i = 0; i < 100; i++) {
            producerService.sendMessage("test" + i);
        }
        context.close();
    }
}

运行消息生产者的代码,到ActiveMQ管理界面上,确认消息已发送到队列中,如下:

如此一来,我们的消息生产者就开发好了。


Spring JMS的使用_2

在上文中,我们已经开发好了生产者,并且也成功发送了消息到队列中。我们接下来开发一个消费者来消费这些消息,首先我们需要实现消息监听器接口:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package org.zero01.jms.consumer;

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

/**
 * @program: jms-spring
 * @description: 消费者消息监听器
 * @author: 01
 * @create: 2018-05-27 10:51
 **/
public class ConsumerMessageListener implements MessageListener {

    /**
     * 接收消息
     * @param message
     */
    public void onMessage(Message message) {
        TextMessage textMessage = (TextMessage) message;
        try {
            System.out.println("接收消息: " + textMessage.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

然后新建一个运行类,作为我们的消息消费者。代码如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package org.zero01.jms.consumer;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @program: jms-spring
 * @description: 消息消费者
 * @author: 01
 * @create: 2018-05-27 10:57
 **/
public class AppConsumer {

    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("consumer.xml");
    }
}

新建consumer.xml配置文件,配置内容如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="common.xml"/>

    <bean id="consumerMessageListener" class="org.zero01.jms.consumer.ConsumerMessageListener"/>
    <!-- 配置消息监听容器 -->
    <bean id="defaultMessageListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"
        p:connectionFactory-ref="connectionFactory"
        p:destination-ref="queueDestination"
        p:messageListener-ref="consumerMessageListener"
    />
</beans>

运行消息消费者的代码,到ActiveMQ管理界面上,确认能够成功从消息队列中消费消息

如此一来,我们的消息消费者也开发好了。


Spring JMS的使用_3

以上演示的是队列模式的开发,接下来我们简单演示一下主题模式。主题模式的代码和队列模式的代码几乎是一样的,区别只在于目的地的配置。在common.xml配置文件中,新增主题模式的目的地:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<!-- 一个主题的目的地,发布/订阅模式 -->
<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
    <!-- 目的地的名称 -->
    <constructor-arg value="topic"/>
</bean>

修改consumer.xml配置文件中,目的地的配置:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<!-- 配置消息监听容器 -->
<bean id="defaultMessageListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"
    p:connectionFactory-ref="connectionFactory"
    p:destination-ref="topicDestination"
    p:messageListener-ref="consumerMessageListener"
/>

最后修改一下 ProducerServiceImpl 实现类中,指定注入的目的地名称:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
...
@Service("producerService")
public class ProducerServiceImpl implements ProducerService {

    @Resource(name = "topicDestination")
    private Destination destination;
    ...
}

完成以上修改后,就已经从队列模式切换到主题模式了。接下来进行一个简单的测试,由于是主题模式的原因,所以我们先运行消费者的代码,然后再运行生产者的代码。运行完毕后,到ActiveMQ管理界面上,确认消费者能够成功从主题中订阅消息,如下:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/05/27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
spring 整合 ActiveMQ
JMS即Java Message Service,Java消息服务。主要用于在生产者和消费者之间进行消息传递,生产者负责产生消息,而消费者负责接收消息。
WindWant
2020/09/11
4670
activeMQ和spring的整合
http://www.cnblogs.com/shuai-server/p/8966299.html  这篇博客中介绍了activemq传递消息的两种方式,今天分享的是activemq框架和spring框架的整合使用。 (1)导入activemq的核心jar包和整合spring需要的两个jar包  context-support和jms.jar(使用spring的版本是4.2.7 activemq的版本是5.11.2) <!--锁定版本号--> <properties>   <spring.version>
用户2146856
2018/05/18
5550
ActiveMQ与spring整合
第二步:配置Activemq整合spring。配置ConnectionFactory applicationContext-activemq.xml
用户5927264
2019/08/01
2820
宜立方商城 第九天Activemq整合springMQ的应用场景
第九天: 1、Activemq整合springMQ的应用场景 2、添加商品同步索引库 3、商品详情页面动态展示 4、展示详情页面使用缓存
周杰伦本人
2022/10/25
2670
宜立方商城 第九天Activemq整合springMQ的应用场景
如何基于消息中间件实现分布式事务?我想说的都在这儿了!!
作者个人研发的在高并发场景下,提供的简单、稳定、可扩展的延迟消息队列框架,具有精准的定时任务和延迟队列处理功能。自开源半年多以来,已成功为十几家中小型企业提供了精准定时调度方案,经受住了生产环境的考验。为使更多童鞋受益,现给出开源框架地址:
冰河
2020/10/29
3K0
如何基于消息中间件实现分布式事务?我想说的都在这儿了!!
activemq的高可用(zookeeper+leveldb)主从集群
ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线。完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现
互扯程序
2018/12/28
2.4K1
JMS学习之路(一):整合activeMQ到SpringMVC
JMS的全称是Java Message Service,即Java消息服务。它主要用于在生产者和消费者之间进行消息传递,生产者负责产生消息,而消费者负责接收消息。把它应用到实际的业务需求中的话我们可以在特定的时候利用生产者生成一消息,并进行发送,对应的消费者在接收到对应的消息后去完成对应的业务逻辑。对于消息的传递有两种类型,一种是点对点的,即一个生产者和一个消费者一一对应;另一种是发布/订阅模式,即一个生产者产生消息并进行发送后,可以由多个消费者进行接收。
肖哥哥
2019/02/22
1.6K1
JMS学习之路(一):整合activeMQ到SpringMVC
JMS--ActiveMQ的简单使用
消息中间件利用高效可靠的消息传递机制进行平台无关的数据交流,并基于数据通信来进行分布式系统的集成。通过提供消息传递和消息排队模型,它可以在分布式环境下扩展进程间的通信。对于消息中间件,常见的角色大致也就有 Producer(生产者)、Consumer(消费者)。消息队列中间件是分布式系统中重要的组件,主要解决应用解耦,异步消息,流量削锋等问题,实现高性能,高可用,可伸缩和最终一致性架构。
宋先生
2019/07/18
1.1K0
activitemq整合spring
image.png activitemq整合spring 一.activmq的点对点模型 image.png pom.xml: <?xml version="1.0" encoding="UTF-8"
Dream城堡
2019/01/28
4860
activitemq整合spring
ActiveMQ学习之Spring整合ActiveMQ------>监听配置
一、pom <dependencies> <!--activemq--> <dependency> <groupId>org.apache.activemq</group
用户5899361
2020/12/07
9460
第二章:ActiveMQ与spring的整合使用
在之前建好的工程的主目录下建一个resource目录,然后建一个配置文件,我这里是activeMq.xml
全栈程序员站长
2022/08/05
2500
第二章:ActiveMQ与spring的整合使用
消息队列中间件(二)使用 ActiveMQ
Active MQ 是由 Apache 出品的一款流行的功能强大的开源消息中间件,它速度快,支持跨语言的客户端,具有易于使用的企业集成模式和许多的高级功能,同时完全支持 JSM1.1 和 J2EE1.4 。
未读代码
2019/11/04
1.7K0
消息队列中间件(二)使用 ActiveMQ
ActiveMQ学习之Spring整合ActiveMQ------>消息主题
一、pom <dependencies> <!--activemq--> <dependency> <groupId>org.apache.activemq</groupI
用户5899361
2020/12/07
2870
ActiveMQ整合Spring框架
  前面文章介绍了ActiveMQ的相关内容,本文介绍ActiveMQ和Spring的整合开发
用户4919348
2019/04/02
9380
ActiveMQ整合Spring框架
干货--JMS(java消息服务)整合Spring项目案例
Sprng-jms消息服务小项目 所需的包: spring的基础包 spring-jms-xx包 spring-message–xx包 commons-collection-xx包 commons-pool2-xx包 aop切面的包: spring-aop,spring-aspect,aopalliance,aspectjrt.jar,aspectjweaver.jar 配置: 1.配置ConnectionFactory 2.
汤高
2018/01/11
1.9K0
干货--JMS(java消息服务)整合Spring项目案例
深入浅出JMS(四)--Spring和ActiveMQ整合的完整实例
第一篇博文深入浅出JMS(一)–JMS基本概念,我们介绍了JMS的两种消息模型:点对点和发布订阅模型,以及消息被消费的两个方式:同步和异步,JMS编程模型的对象,最后说了JMS的优点。
程序猿小亮
2021/01/29
5900
五分钟快速了解ActiveMQ,案例简单且详细!
window版本的解压后双击/bin/activemq.bat 即可启动。 或者以服务方式启动:右键管理员运行InstallService.bat,然后在Windows系统的服务中启动。
Mshu
2019/07/02
9800
五分钟快速了解ActiveMQ,案例简单且详细!
Spring JMS---三种消息监听器
链接:https://blog.csdn.net/u012562943/article/details/51424232
用户5224393
2019/08/13
2.5K0
day75_淘淘商城项目_08_同步索引库问题分析 + ActiveMQ介绍/安装/使用 + ActiveMQ整合spring + 使用ActiveMQ实现添加商品后同步索引库_匠心笔记
方案一:在taotao-manager中,添加商品的业务逻辑中,添加一个同步索引库的业务逻辑。
黑泽君
2018/12/18
9970
ActiveMQ+Spring工程创建详解(附工程文件)
ActiveMQ是Apache所提供的一个开源的消息系统,完全采用Java来实现,因此,它能很好地支持J2EE提出的JMS(Java Message Service,即Java消息服务)规范。JMS是一组Java应用程序接口,它提供消息的创建、发送、读取等一系列服务。JMS提供了一组公共应用程序接口和响应的语法,类似于Java数据库的统一访问接口JDBC,它是一种与厂商无关的API,使得Java程序能够与不同厂商的消息组件很好地进行通信。
迹_Jason
2019/05/30
5420
推荐阅读
相关推荐
spring 整合 ActiveMQ
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文