java 同步消息服务_spring整合JMS实现同步收发消息(基于ActiveMQ的实现)

本文详述了如何使用Spring整合Java消息服务(JMS)和ActiveMQ来实现同步收发消息。首先介绍了ActiveMQ的安装和配置,接着讲解了Spring工程的配置,包括pom文件、连接工厂、JmsTemplate的设置。然后展示了生产者和消费者的实现,通过JmsTemplate的send和receive方法实现消息的发送和接收。最后,文中还讨论了同步模式下消费者逐条消费消息的限制及其对效率的影响。
摘要由CSDN通过智能技术生成

本文介绍了spring整合JMS实现同步收发消息(基于ActiveMQ的实现),分享给大家,具体如下:

1. 安装ActiveMQ

注意:JDK版本需要1.7及以上才行

到Apache官方网站下载最新的ActiveMQ的安装包,并解压到本地目录下,下载链接如下:http://activemq.apache.org/download.html,解压后的目录结构如下:

bin目录结构如下:

49dc44637f0ff2c0837b9ae1ed55b577.png

b036880211b2a2e08b9bd7af15e32447.png

如果我们是32位的机器,就双击win32目录下的activemq.bat,如果是64位机器,则双击win64目录下的activemq.bat,运行结果如下:

77466e92b29f8a0c92fbae8333dec227.png

启动成功!成功之后在浏览器输入http://127.0.0.1:8161/地址,可以看到ActiveMQ的管理页面,用户名和密码默认都是admin,如下:

5673eee77932c640df1fb7e6a491beae.png

2. 新建一个Maven工程,并配置pom文件如下:

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

com.chhliu.myself

activemq_start

0.0.1-SNAPSHOT

jar

activemq_start

http://maven.apache.org

UTF-8

3.2.5.RELEASE

junit

junit

4.10

test

org.springframework

spring-context

${spring-version}

org.springframework

spring-jms

${spring-version}

org.springframework

spring-test

${spring-version}

javax.annotation

jsr250-api

1.0

org.apache.activemq

activemq-all

5.13.3

org.apache.commons

commons-pool2

2.0

3. 配置连接工厂(ConnectionFactory)

Spring给我们提供了如下的连接工厂:

b136c1165920fbbea218cf7761b784c2.png

其中SingleConnectionFactory保证每次返回的都是同一个连接,CachingConnectionFactory继承了SingleConnectionFactory,在保证同一连接的同时,增加了缓存的功能,可以缓存Session以及生产者,消费者。当然,JMS提供的连接工厂只是用来实现管理的,并不是真正连接MQ的,真正的连接工厂需要具体的MQ厂商提供,下面我们以ActiveMQ为例来说明,配置如下:

class="org.springframework.jms.connection.SingleConnectionFactory">

为了减少我们连接的资源消耗,ActiveMQ为我们提供了一个连接工厂管理池--PooledConnectionFactory,通过连接工厂池,可以将Connection,Session等都放在池里面,用的时候直接返回池里面的内容,无需临时建立连接,节约开销。配置如下:

class="org.springframework.jms.connection.SingleConnectionFactory">

4. 配置JmsTemplate

配置好连接工厂之后,就需要配置JMS的JmsTemplate,JmsTemplate的作用和JdbcTemplate类似,我们发送和接收消息,都是通过JmsTemplate来实现的,配置如下:

5. 生产者实现

配置完这些之后,我们就可以写代码实现生产者和消费者了,生产者主要用来生产消息,并向目的队列中推送消息,接口定义如下:

public interface ProducerService {

void sendMessage(Destination destination, final String message);

}

实现类代码如下:

@Service("producerServiceImpl")

public class ProducerServiceImpl implements ProducerService {

/**

* 注入JmsTemplate

*/

@Resource(name="jmsTemplate")

private JmsTemplate jTemplate;

/**

* attention:

* Details:发送消息

* @author chhliu

* 创建时间:2016-7-28 下午2:33:14

* @param destination

* @param message

*/

@Override

public void sendMessage(Destination receivedestination, final String message) {

System.out.println("================生产者创建了一条消息==============");

jTemplate.send(receivedestination, new MessageCreator() {

@Override

public Message createMessage(Session session) throws JMSException {

return session.createTextMessage("hello acticeMQ:"+message);

}

});

}

}

6. 消费者实现

假设生产者已经创建了一条消息,并推送到了对应的队列中,消费者需要从这个队列中取出消息,并同时回复一条报文,自己已经收到了这条消息,为了测试回复报文的功能,我们下面会将回复报文放到另一个队列中,此例使用同步接收消息的方式,而不是异步监听的方式实现,接口定义如下:

public interface ConsumerService {

String receiveMessage(Destination destination, Destination replyDestination);

}

实现类代码如下:

@Service("consumerServiceImpl")

public class ConsumerServiceImpl implements ConsumerService {

/**

* 注入JmsTemplate

*/

@Resource(name="jmsTemplate")

private JmsTemplate jTemplate;

/**

* attention:

* Details:接收消息,同时回复消息

* @author chhliu

* 创建时间:2016-7-28 下午2:39:45

* @param destination

* @return

*/

@Override

public String receiveMessage(Destination destination, Destination replyDestination) {

/**

* 接收消息队列中的消息

*/

Message message = jTemplate.receive(destination);

try {

/**

* 此处为了更好的容错性,可以使用instanceof来判断下消息类型

*/

if(message instanceof TextMessage){

String receiveMessage = ((TextMessage) message).getText();

System.out.println("收到生产者的消息:"+receiveMessage);

/**

* 收到消息之后,将回复报文放到回复队列里面去

*/

jTemplate.send(replyDestination, new MessageCreator() {

@Override

public Message createMessage(Session session) throws JMSException {

return session.createTextMessage("消费者已经收到生产者的消息了,这是一条确认报文!");

}

});

return receiveMessage;

}

} catch (JMSException e) {

e.printStackTrace();

}

return "";

}

}

生产者和消费者实现之后,我们要做的就是配置队列了,下面给出项目完整的配置文件:

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" xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:p="http://www.springframework.org/schema/p" xmlns:cache="http://www.springframework.org/schema/cache"

xmlns:jpa="http://www.springframework.org/schema/data/jpa"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.2.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.2.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.2.xsd

http://www.springframework.org/schema/cache

http://www.springframework.org/schema/cache/spring-cache-3.2.xsd

http://www.springframework.org/schema/data/jpa

http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd">

NTF_MOCK_INPUT

NTF_MOCK_OUTPUT

到这里,所有的代码和配置文件就都整好了,下面就是进行测试,测试代码如下:

生产者测试代码:

package com.chhliu.myself.activemq.start.sync;

import javax.annotation.Resource;

import javax.jms.Destination;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations = { "classpath:applicationContext.xml" })

public class SyncProducerActiveMQTest {

@Resource(name="producerServiceImpl")

private ProducerService pService;

@Resource(name="queueDestination")

private Destination receiveQueue;

@Test

public void producerTest(){

pService.sendMessage(receiveQueue, "my name is chhliu!");

}

}

消费者测试代码:

package com.chhliu.myself.activemq.start.sync;

import javax.annotation.Resource;

import javax.jms.Destination;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations = { "classpath:applicationContext.xml" })

public class SyncConsumerActiveMQTest {

@Resource(name="consumerServiceImpl")

private ConsumerService cService;

@Resource(name="queueDestination")

private Destination receiveQueue;

@Resource(name="responseQueue")

private Destination replyQueue;

@Test

public void producerTest(){

String result = cService.receiveMessage(receiveQueue, replyQueue);

System.out.println(result);

}

}

测试结果如下:

生产者测试结果:

================生产者创建了一条消息==============

消费者测试结果:

收到生产者的消息:hello acticeMQ:my name is chhliu!

hello acticeMQ:my name is chhliu!

再来看下ActiveMQ的管理页面的结果:

fd3a800a135915abdac1b59809b5f23a.png

从管理页面中可以看到,生产者生产了消息,并且入队列了,同时消费者也消费了消息,并将回复消息放到了回复队列中,测试成功。

但是这种同步取消息的方式有个缺点,每次只会取一条消息消费,取完之后就会一直阻塞,下面来测试一下:首先让生产者再生产5条消息,然后运行消费者程序,发现会只消费一条消息,除非我们在消费者程序里面加while(true),一直轮询队列,这种实现方式不仅耗内存,效率也不是很高,后面,我们会对这种方式进行改进,使用异步监听模式,测试效果如下:

生产者创建了5条消息:

=======生产者创建了一条消息========

=======生产者创建了一条消息========

=======生产者创建了一条消息========

=======生产者创建了一条消息========

======生产者创建了一条消息=========

ActiveMQ管理页面如下:

aabfb6af8afd6853f47519b49f2e4d34.png

消费者消费一条消息:

收到生产者的消息:hello acticeMQ:my name is chhliu!

hello acticeMQ:my name is chhliu!

消费者消费消息后,ActiveMQ管理页面如下:

3c6659b7d2f4a41f83d37ad1a59dba26.png

从上面的对比中,我们可以看出来,同步模式下,消费者消费消息时,是逐条消费,每次只消费一条消息。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值