ActiveMQ介绍及Spring整合实例

(四) Spring整合ActiveMQ---超详细教程 Spring整合ActiveMQ环境配置Spring整合ActiveMQ之队列生产者Spring整合ActiveMQ之队列消费者三级目录 前面三节讲了ActiveMQ的安装、测试。JMS介绍以及四大组成元素,还有ActiveMQ的可靠性(持久化、事务、签收),还有Broker等等。 但是光学会还不够,我们还要把ActiveMQ应用到我们已有的框架中,如Spring和SpringBoot等等。 这一节主要学习如何在Spring中使用ActiveMQ。 环境配置 首先创建一个spring项目,在pom文件中导入 阅读详情

前言

ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线。ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现。主要解决进场通讯,应用耦合,流量削锋。实现高性能,高可用,可伸缩和最终一致性架构。异步消息是一个应用程序向另外一个应用程序间接发送消息的一种方式,这种方式无需等待对方的相应。比如用户注册之后发送短信,秒杀程序的流量削锋,聊天室的消息通讯,复杂耗时的程序的而无须立即返回的结果的程序之间的通讯。

消息模型

ActiveMQ遵循了JMS规范,有两种消息模型,点对点和发布订阅模型。

点对点:在点对点模型中,每一条消息都会有一个发送者和一个接受者。当消息代理得到消息时,它将消息放入一个队列中。当接收者请求队列中的下一条消息时,消息会从队列中取出,并投递给接收者。因为消息投递后会从队列删除,这样就可以保证消息只能投递给一个接收者。如图:
image
尽管消息队列中每一条消息只被投递给一个接收者,但是并不意味着只能使用一个接收者从队列中获取消息。通常可以使用几个接收者来处理队列中的消息,有点像银行办理业务,自己的业务就是一个消息,选取一个空闲的窗口办理业务。

发布-订阅模型:消息会发生给一个主题。与队列类似,多个接收者都可以监听一个主题。但是,与队列不同的是,消息不再是只投递给一个接收者,而是主题的所有订阅者都会接收到此消息的副本。如图:
image
有点像杂志的发行商和杂志订阅者的关系。

ActiveMQ下载

下载地址http://activemq.apache.org/download.html
注意:Java Runtime Environment (JRE) JRE 1.7 (1.6 for version <=5.10.0)
5.10以上的版本需要java1.7以上的环境。
安装后在http://localhost:8161 (本机)可查看控制台
下面来代码整合。

maven配置

<dependencies>
     <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jms</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-messaging</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>


    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-all</artifactId>
        <version>5.14.4</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>
      <!--spring单元测试依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>


  </dependencies>

实体类

package com.study.entity;

import java.io.Serializable;

public class TestMessage implements Serializable{

    private static final long serialVersionUID = -2132582539599141027L;

    private Integer id;
    private String msg;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    @Override
    public String toString() {
        return "TestMessage [id=" + id + ", msg=" + msg + "]";
    }


}

ActiveMQ配置

ActiveMQ有自己的spring配置文件命名空间。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:amq="http://activemq.apache.org/schema/core"
    xmlns:jms="http://www.springframework.org/schema/jms"
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd   
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/jms
        http://www.springframework.org/schema/jms/spring-jms-4.3.xsd
        http://activemq.apache.org/schema/core
        http://activemq.apache.org/schema/core/activemq-core-5.14.4.xsd">

        <context:component-scan base-package="com.study"></context:component-scan>
        <!-- 声明连接工厂 -->
        <amq:connectionFactory id="targetConnectionFactory" brokerURL="tcp://localhost:61616" userName="admin" password="admin" trustAllPackages="true" />

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

        <!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->
        <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
            <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
            <property name="connectionFactory" ref="connectionFactory"/>
        </bean>

        <!-- 消息监听器容器 -->
        <jms:listener-container connection-factory="connectionFactory">
            <jms:listener destination="study.queue.simple" ref="consumerService" method="receiveMessage"/>
            <jms:listener destination="study.queue.simple" ref="consumerService" method="receiveMessage2"/>
            <jms:listener destination="study.queue.object" ref="consumerService" method="receiveObject" />
        </jms:listener-container>

        <jms:listener-container connection-factory="connectionFactory" destination-type="topic">
            <jms:listener destination="study.topic.simple" ref="consumerService" method="receiveTopicMessage"/>
            <jms:listener destination="study.topic.simple" ref="consumerService" method="receiveTopicMessage2"/>
        </jms:listener-container>

</beans>  

Spring提供了JmsTemplate来简化JMS的开发。所以需要声明JmsTemplate的bean,已经所依赖的connectionFactory。
上面brokerURL需填写activeMQ安装的地址,因为我是本地安装,所以这么写。消息监听器容器中声明了接收者其中destination声明一个queue或者topic名称。ref声明接收者的类 ,method声明方法。如果该类继承了MessageListener则可以不用写method方法,会默认调用onMessage()方法来接收消息。

Producer代码

package com.study.producer;

import com.study.entity.TestMessage;


public interface ProducerService {
    /**
     * 发送queue文本消息
     * @param destination
     * @param message
     */
    public void sendMessage(String destinationName,String message);
    /**
     * 发送queue对象消息
     * @param destinationName
     * @param testMessage
     */
    public void sendMessage(String destinationName,TestMessage testMessage);
    /**
     * 发送topic文本消息
     * @param destinationName
     * @param message
     */
    public void sendTopicMessage(String destinationName, String message);

}
package com.study.producer.impl;

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

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

import com.study.entity.TestMessage;
import com.study.producer.ProducerService;

@Component
public class ProducerServiceImpl implements ProducerService{

    @Resource
    private JmsTemplate jmsTemplate;


    public void sendMessage(String destinationName,  final String message) {
        System.out.println("生产方发送字符串消息:"+message);
        jmsTemplate.send(destinationName, new MessageCreator() {

            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(message);
            }
        });

    }

    public void sendMessage(String destinationName, final TestMessage testMessage) {
        System.out.println("生产方发送对象消息:"+testMessage);

        /*jmsTemplate.send(destinationName, new MessageCreator() {

            public Message createMessage(Session session) throws JMSException {
                return session.createObjectMessage(testMessage);
            }
        });*/
        jmsTemplate.convertAndSend(destinationName, testMessage);
    }

    public void sendTopicMessage(String destinationName, String message){
        System.out.println("生产方发送文本消息:"+message);
        jmsTemplate.setPubSubDomain(true);
        jmsTemplate.convertAndSend(destinationName, message);
    }

}

上面代码中使用了jmsTemplate.send()和jmsTemplate.convertAndSend()方法。JMS在发送消息的时候,传送的对象是Message对象,MessageCreator提付了自定义消息与Message的转换。而convertAndSend()会内置消息转换器,所以不用传入MessageCreator作为参数。默认的消息转换器是SimpleMessageConverter,可以自己实现或者使用spring提供的其他转换器来配置消息的转换。

Consumer代码

package com.study.consumer;

import com.study.entity.TestMessage;

public interface ConsumerService {
    /**
     * 消费方 接受字符串
     * @param message
     */
    public void receiveMessage(String message);
    /**
     * 消费方 接受对象
     * @param message
     */
    public void receiveObject(TestMessage testMessage);

    /**
     * 消费方 topic 接受字符串
     * @param message
     */
    public void receiveTopicMessage(String message);

    /**
     * 消费方 topic 接受字符串
     * @param message
     */
    public void receiveTopicMessage2(String message);

}
package com.study.consumer.impl;

import org.springframework.stereotype.Component;

import com.study.consumer.ConsumerService;
import com.study.entity.TestMessage;
@Component("consumerService")
public class ConsumerServiceImpl implements ConsumerService{


    public void receiveMessage(String message) {
        System.out.println("消费方接收消息1:"+message);
    }
    public void receiveMessage2(String message) {
        System.out.println("消费方接收消息2:"+message);
    }

    public void receiveObject(TestMessage testMessage) {
        System.out.println("消费方接收对象:"+ testMessage);
    }


    public void receiveTopicMessage(String message) {
        System.out.println("topic消费方接收消息1:"+message);
    }
    public void receiveTopicMessage2(String message) {
        System.out.println("topic消费方接收消息2:"+message);

    }

}

将接受的类型放入接收者方法参数里面就可直接获取到消息,并且完成转换。

测试类

package com.test;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = { "classpath:activemq.xml" })  
@RunWith(SpringJUnit4ClassRunner.class)  
public class SpringTestCase extends AbstractJUnit4SpringContextTests {

}
package com.test;

import javax.annotation.Resource;

import org.junit.Test;

import com.study.entity.TestMessage;
import com.study.producer.ProducerService;

public class ActivemqTest extends SpringTestCase{

    @Resource
    private ProducerService producerService;

    @Test
    public void simpleSend(){
        producerService.sendMessage("study.queue.simple", "简单文本消息测试");
    }

    @Test
    public void ObjectSend(){
        TestMessage testMessage = new TestMessage();
        testMessage.setId(1);
        testMessage.setMsg("对象消息。。。");
        producerService.sendMessage("study.queue.object", testMessage);
    }

    @Test
    public void simpleTopicSend(){
        producerService.sendTopicMessage("study.topic.simple", "topic简单文本消息测试");
    }
}

测试simpleSend()方法。发送一条文本消息,发送的目的是study.queue.simple。从我们的avtivemq.xml配置文件中可以看到

<jms:listener destination="study.queue.simple" ref="consumerService" method="receiveMessage"/>
<jms:listener destination="study.queue.simple" ref="consumerService" method="receiveMessage2"/>

study.queue.simple有两个接受者,而jmsTemplate发送默认是点对点模型,所以是receiveMessage与receiveMessage2随机获取到消息。多次执行simpleSend()查看结果:
image
image
好吧,我试了好几次,刚开始一直是2

测试ObjectSend() 方法发送了我们的自定义对象。发送目的是study.queue.object执行结果如图:
image
可以看到接收方直接获取到对象。

测试simpleTopicSend(),发送目的是study.topic.simple,配置文件中接收方配置

<jms:listener-container connection-factory="connectionFactory" destination-type="topic">
    <jms:listener destination="study.topic.simple" ref="consumerService" method="receiveTopicMessage"/>
    <jms:listener destination="study.topic.simple" ref="consumerService" method="receiveTopicMessage2"/>
</jms:listener-container>

而且在发送的时候声明了发布订阅消息模型

jmsTemplate.setPubSubDomain(true);
jmsTemplate.convertAndSend(destinationName, message);

接收者有两个,并且是发布订阅模型,所以这两个接收者都应该接收到消息,执行结果如图:
image

本例子是单元测试的例子,对应jmsTemplate只使用了一个,每次执行单元测试都是重新运行,所以默认点对点模型没问题,但是因为spring的单例的原因,项目集成时,对应jmsTemplate应该手动声明相应消息模型,或配置多个jmsTemplate。

代码下载:http://download.youkuaiyun.com/detail/poorcoder_/9776505
转载请标明出处:http://blog.youkuaiyun.com/poorcoder_/article/details/61192791

白话机器学习算法理论+实战番外篇之Xgboost 1. 写在前面 如果想从事数据挖掘或者机器学习的工作,掌握常用的机器学习算法是非常有必要的,在这简单的先捋一捋, 常见的机器学习算法: 监督学习算法:逻辑回归,线性回归,决策树,朴素贝叶斯,K近邻,支持向量机,集成算法Adaboost等 无监督算法:聚类,降维,关联规则, PageRank等 我前面已经尝试用最白话的语言完成了一个白话机器学习算法理论+实战系列,这个系列已经基本包含了上面这些算... 阅读详情

相关推荐

Vue中实现word文档渲染、在线编辑、保存

Vue3对word文档进行渲染、编辑、保存。word转成html,html转成word

h18749849699的博客 1331

Spring+ActiveMQ

Spring集成ActiveMQ实现消息发送,两种消息模型和三种消息类型。

weixin_44929475的博客 1287

ENSP从下载到运行:用虚拟机搭建华为认证实验环境全流程(含USG6000V镜像配置)

本文提供了一份详细的华为ENSP仿真平台从下载、安装到配置USG6000V防火墙镜像的完整指南。内容涵盖前置软件安装、ENSP主程序配置、核心设备镜像导入及虚拟机资源分配策略,旨在帮助网络工程师和学习者快速搭建一个稳定、功能齐全的华为认证实验环境,为备考和模拟企业网络部署打下坚实基础。

weixin_29230865的博客 539

六、Spring/Spring Boot整合ActiveMQ

Spring/Spring Boot整合ActiveMQ一、Spring整合ActiveMQ1.pom.xml2.Queue - 队列2.1 applicationContext.xml2.2 生产者2.3 消费者3.Topic - 主题3.1 applicationContext.xml3.2 生产者3.3 消费者4.消费者 - 监听器4.1 编写监听器类4.2 配置监听器4.3 生产者+消费者一体二、Spring Boot整合ActiveMQ1.Queue - 队列1.1 生产者1.1.1 创建Mave

青啊青斯博客 3264

AMBA VIP基础使用方式(AXI)

AXI环境配置 1)基础配置 作为master或者slave使用时,对应的is_active = 1 只作为i监测(monitor)使用时,对应slave_cfg的is_active = 0(对应端口连接也有所区别) class smu_axi_cfg extends svt_axi_system_configuration; `uvm_object_utils(smu_aix_cfg) function new(string name="smu_axi_cfg); super.new(n..

qq_37573794的博客 7984

泛微OA与金蝶云星空深度集成实战:审批与表单双场景解析

本文深入解析泛微OA与金蝶云星空的深度集成实战,聚焦审批流程与表单对接两大核心场景。通过具体案例,详细阐述了如何实现业务数据与审批流程的自动联动,打破数据孤岛,提升企业运营效率与数据一致性,并分享了接口设计、安全策略及实战避坑指南。

4k5l6j7h8的博客 469

Spring整合ActiveMq

1、概述 多种语言和协议编写客户端。语言: Java, C, C++, C#, Ruby, Perl, Python, PHP。应用协议: OpenWire,Stomp REST,WS Notification,XMPP,AMQP 完全支持JMS1.1和J2EE 1.4规范 (持久化,XA消息,事务) 对Spring的支持,ActiveMQ可以很容易内嵌到使用Spring的系统里面去,而且也支持Spring2.0的特性 通过了常见J2EE服务器(如 Geronimo,JBoss 4, GlassFish,W

马小果v:ma-xiaoguo的博客 1012

Python RK3588 MPP 8路视频硬解码!全体目光向我看齐!

本文重写了官方demo、加入了Zlmediakit进行拉流并通过pybind11将代码封装成so库,现在,在python中直接通过import的方式,就能完成基础的拉流解码操作,目前支持8路拉流解码!!!

m0_46303486的博客 4881

Spring与ActiveMQ整合实例源码

Spring与ActiveMQ整合实例源码 去发现同类优质开源项目:https://gitcode.com/ 此仓库包含一个基于Spring框架、JMS(Java消息服务)、ActiveMQ及Tomcat的整合实例源码。该实例采用注解方式实现,并提供所需jar包,旨在帮助开发者学习和掌握Spring与ActiveMQ的整合应用。 特点 基于Spring框架,便于管理和维护 使用JMS进行消息传递...

gitblog_06745的博客 687

AI智能体在化学中的伦理问题:7个案例,架构师如何应对?

AI在化学中的应用早已不是新鲜事:药物发现中用AI预测分子活性(比如AlphaFold预测蛋白质结构)、化工生产中用AI优化合成路线(降低成本30%+)、材料研发中用AI设计新型电池材料(缩短研发周期5年)……但随着AI从“辅助工具”升级为“自主决策智能体”(比如能自动调整反应条件的“化学机器人”),伦理风险开始从“潜在隐患”变成“真实事故”。AI在化学中会踩哪些伦理“坑”?(用案例具象化)这些“坑”的底层逻辑是什么?(从技术到价值观的链条)架构师能做什么?

AI 算法实战派 1364

语音算法面试复习系列3——语音识别基础 + CTC 详解

摘要:本文系统讲解了语音识别(ASR)的核心算法CTC。主要内容包括:1) ASR的核心挑战是输入音频帧与输出文字序列的对齐问题;2) CTC通过引入blank标记和动态规划算法,无需对齐标注即可训练;3) 详细解析CTC前向算法实现路径概率求和,以及贪心和Beam Search解码方法;4) 指出CTC的条件独立性假设导致无法建模输出依赖关系;5) 对比CTC与传统方法和Attention/Transducer的优缺点,分析实际应用中的subsampling技术。文章包含数学推导、代码实现和面试常见问题,

m0_60605453的博客 307

Spring整合ActiveMQ实例

若需要了解ActiveMQ的安装过程和单独使用实例,可以查看我之前的文章 二者整合思路 Spring最厉害的地方就是它的Bean了,还有它特有的IOC(控制反转)和AOP(面向切面编程)技术。有了这些,我们就可以不用new关键字构造对象,同时,可以方便地使用注入往类中的属性进行初始化。如果你编写过ActiveMQ之类的JMS应用程序,无论对于消息的生产者还是消费者,最重要的接口有以下两个: ...

Keven_Ma的博客 389

LPDDR5 学习笔记05:WCK操作详解

LPDDR5 SDRAM采用双时钟设计,写时钟(WCK)频率为命令时钟(CK)的2倍或4倍,需要通过WCK2CK同步机制解决时钟域对齐问题。该同步操作由带特殊标志位的CAS命令触发,控制器需提供半频WCK脉冲进行状态校准。同步完成后才能执行读写操作,且支持多存储体组同步和WCK常开模式以优化性能。掉电后必须重新执行同步流程,确保时钟域正确对齐。该机制有效解决了高速内存接口的时序挑战,为LPDDR5性能提升提供关键技术支撑。

一只豌豆象的博客 2008

深入浅出JMS(四)--Spring和ActiveMQ整合的完整实例

http://blog.youkuaiyun.com/jiuqiyuliang/article/details/48758203

专栏 1523

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

深入浅出JMS--Spring和ActiveMQ整合的完整实例

前言 这篇博文,我们基于Spring+JMS+ActiveMQ+Tomcat,做一个Spring4.1.0和ActiveMQ5.11.1整合实例,实现了Point-To-Point的异步队列消息和PUB/SUB(发布/订阅)模型,简单实例,不包含任何业务。 环境准备 工具 JDK1.6或1.7 Spring4.1.0 ActiveMQ5.11.1 To...

友桥的博客 1111

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Spring和ActiveMQ整合的完整实例

第一篇博文,我们介绍了JMS的两种消息模型:点对点和发布订阅模型,以及消息被消费的两个方式:同步和异步,JMS编程模型的对象,最后说了JMS的优点。 第二篇博文,我们介绍了消息中间件ActiveMQ,安装,启动,以及优缺点。 第三篇博文,我们实现了一种点对点的同步消息模型,并没有给大家呈现发布订阅模型。 前言 这篇博文,我们基于Spring+JMS+ActiveMQ+T

ptsx0607的专栏 291

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

ActiveMQ在spring中整合实例讲解

ActiveMQ与Spring整合使用实例,希望对初学者能有一定帮助。

博茨瓦纳的狮王 2224

Spring整合ActiveMQ与Quartz的实例

 这两天在项目中有一个任务,需要灵活配置调度任务时间,并能自由启动或停止调度(下载:实例源代码)。顺便总结一下:applicationContext-activemq.xml: http://www.springframework.org/schema/beans" xmlns:amq="http://activemq.org/config/1.0" xmlns:xsi="http

telecamera的专栏 3057

关于JMS与SPRING的整合实例(基于Apache ActiveMQ)

原文地址:http://dreamforce.me/archives/450

538

spring中整合activeMQ实例介绍

以前代码,为个人实际项目中所有,均亲测成功1.配置消费者spring-activemq-producer.xml,这里有两个消息队列<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework....

weixin_41325595的博客 188

Spring ActiveMQ整合实例

Spring + ActiveMQ实现生产者消费者模式和发布订阅模式 环境准备 安装最新版ActiveMQ Jdk1.8 Spring 创建工程 通过gradle构建项目 引入依赖包 在build.gradle文件中加入以下依赖 //spring [group: 'org.springframework', name: 'spring-aop',

sinat_23324343的博客 309
上一篇: Spring整合Redis用作缓存-注解方式
下一篇: SSM整合SpringSecurity实现权限管理实例 javaconfig配置方式
poorCoder_
博客等级 码龄10年 129粉丝 41原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值