JMS生产者消费者模式收发通用类

本文介绍如何利用ActiveMQ作为消息提供者,通过JMS API实现消息队列的异步和同步发送,包括发送不支持特定消息、关联消息ID及带特定属性的消息,并提供了相应的API方法和使用示例。

jms提供者为ActiveMQ

 

import java.util.Map;
import java.util.UUID;

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

import org.apache.activemq.command.ActiveMQQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

/**
 * mq通用类
 * 
 * @author Fu Wei
 * 
 */
@Component
public class ActiveMQQueueCommon {
	private static final Logger LOG = LoggerFactory.getLogger(ActiveMQQueueCommon.class);

	@Autowired
	private JmsTemplate jmsTemplate;

	/**
	 * 异步发送 不支持特定消息
	 * 
	 * @param reqQueue
	 * @param text
	 */
	public void asyncSend(ActiveMQQueue reqQueue, final String text) {
		LOG.debug("发送的XML文内容:{}", text);
		final String correlationId = UUID.randomUUID().toString();
		jmsTemplate.send(reqQueue, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				TextMessage msg = session.createTextMessage(text);
				msg.setJMSCorrelationID(correlationId);
				return msg;
			}
		});
	}

	/**
	 * 异步发送,关联消息id
	 * 
	 * @param reqQueue
	 * @param text
	 * @param propertyName
	 * @param propertyValue 支持一个特定消息
	 */
	public void asyncSend(ActiveMQQueue reqQueue, final String text, final String propertyName,
	        final String propertyValue) {
		LOG.debug("发送的XML文内容:{}", text);
		final String correlationId = UUID.randomUUID().toString();
		jmsTemplate.send(reqQueue, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				TextMessage msg = session.createTextMessage(text);
				msg.setJMSCorrelationID(correlationId);
				msg.setStringProperty(propertyName, propertyValue);
				return msg;
			}
		});
	}

	/**
	 * 异步发送,关联消息id
	 * 
	 * @param reqQueue
	 * @param text
	 * @param propertyName
	 * @param propertyMap 选择器参数
	 */
	public void asyncSend(ActiveMQQueue reqQueue, final String text, final String propertyName,
	        final Map<String, String> propertyMap) {
		LOG.debug("发送的XML文内容:{}", text);
		final String correlationId = UUID.randomUUID().toString();
		jmsTemplate.send(reqQueue, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				TextMessage msg = session.createTextMessage(text);
				msg.setJMSCorrelationID(correlationId);
				if (propertyMap != null && propertyMap.size() > 0) {
					for (Map.Entry<String, String> map : propertyMap.entrySet()) {
						msg.setStringProperty(map.getKey(), map.getValue());
					}
				}
				return msg;
			}
		});
	}

	/**
	 * 同步发送,不带消息特定属性
	 * 
	 * @param reqQueue
	 * @param resQueue
	 * @param messText
	 * @param timeout
	 * @return
	 * @throws JMSException
	 */
	public String syncSend(ActiveMQQueue reqQueue, final ActiveMQQueue resQueue, final String messText, long timeout) {
		return syncSend(reqQueue, resQueue, messText, timeout, null);
	}

	/**
	 * 同步发送,带消息特定属性
	 * 
	 * @param reqQueue
	 * @param resQueue
	 * @param messText
	 * @param timeout
	 * @param propertyName
	 * @param propertyValue
	 * @return
	 * @throws JMSException
	 */
	public String syncSend(ActiveMQQueue reqQueue, final ActiveMQQueue resQueue, final String messText, long timeout,
	        final Map<String, String> propertyMap) {
		LOG.debug("转发的消息:{}, 超时时间:{}", messText, timeout);
		final String correlationId = UUID.randomUUID().toString();
		jmsTemplate.send(reqQueue, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				TextMessage msg = session.createTextMessage(messText);
				msg.setJMSReplyTo(resQueue);
				msg.setJMSCorrelationID(correlationId);
				// 添加消息特定属性
				if (propertyMap != null && propertyMap.size() > 0) {
					for (Map.Entry<String, String> map : propertyMap.entrySet()) {
						msg.setStringProperty(map.getKey(), map.getValue());
					}
				}
				return msg;
			}
		});
		jmsTemplate.setReceiveTimeout(timeout * 1000);
		TextMessage recvMsg = (TextMessage) jmsTemplate.receiveSelected(resQueue, "JMSCorrelationID = '"
		        + correlationId + "'");
		String recvMessText = null;
		try {
			recvMessText = recvMsg.getText();
		} catch (JMSException e) {
			LOG.error("jms错误", e);
		}
		LOG.debug("propertyMap: {}, 返回的信息:{}", propertyMap, recvMessText);
		return recvMessText;
	}
}
 

 

什么是消息 消息是一个用于在组件和应用程序之间通讯的的方法。消息之间的传递是点对点的。任何终端之间都可以相互接受和发送消息。并且每个终端都必须遵守如下的规则 -> 创建消息 -> 发送消息 -> 接收消息 -> 读取消息 为什么要使用消息 理由很简单,消息是一个分布式的低耦合通讯方案。A发送一个消息到一个agent ,B作为接受者去agent上获取消息。但是A,B不需要同时到agent上去注册。agent作为一个中转为A,B提供搞效率的通讯服务。 Java消息服务支持两种消息模型:Point-to-Point消息(P2P)和发布订阅消息(Publish Subscribe messaging,简称Pub/Sub)。JMS规范并不要求供应商同时支持这两种消息模型,但开发者应该熟悉这两种消息模型的优势与缺点。 企业消息产品(或者有时称为面向消息的中间件产品)正逐渐成为公司内操作集成的关 键组件。这些产品可以将分离的业务组件组合成一个可靠灵活的系统。 除了传统的 MOM 供应商,企业消息产品也可以由数据库供应商和许多与网络相关的公 司来提供。 Java 语言的客户端和 Java 语言的中间层服务必须能够使用这些消息系统。JMSJava 语言程序提供了一个通用的方式来获取这些系统。 JMS 是一个接口和相关语义的集合,那些语义定义了 JMS 客户端如何获取企业消息产品 的功能。 由于消息是点对点的,所以 JMS 的所有用户都称为客户端(clients)。JMS 应用由定义 消息的应用和一系列与他们交互的客户端组成。
JMSJava Message Service)消费者JMS 系统中的核心组件之一,负责接收消息。 ### 使用方法 从 JMS 应用的一般流程来看,使用 JMS 消费者的步骤如下: 1. 初始化 JMS 连接。 2. 创建会话。 3. 选择消息模型,若选择点对点模型则创建队列。 4. 创建生产者/消费者(这里即为消费者)。 5. 接收消息。 6. 处理消息,判断消息处理是否完成,若完成则关闭连接,未完成则继续接收消息。 ```mermaid graph LR A[初始化 JMS 连接] --> B[创建会话] B --> C{选择消息模型} C -->|点对点| E[创建队列] E --> G[创建生产者/消费者] G --> H[发送/接收消息] H --> I{消息处理完成?} I -->|是| J[关闭连接] I -->|否| H ``` 上述流程代码化示例如下: ```java import javax.jms.*; import org.apache.activemq.ActiveMQConnectionFactory; public class JMSConsumerExample { public static void main(String[] args) { try { // 初始化 JMS 连接 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616"); Connection connection = connectionFactory.createConnection(); connection.start(); // 创建会话 Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 创建队列 Destination destination = session.createQueue("TestQueue"); // 创建消费者 MessageConsumer consumer = session.createConsumer(destination); // 接收消息 Message message = consumer.receive(); if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; System.out.println("Received: " + textMessage.getText()); } // 关闭连接 consumer.close(); session.close(); connection.close(); } catch (JMSException e) { e.printStackTrace(); } } } ``` ### 原理 JMS 消费者的原理涉及监听机制、并发控制与事务处理。消费者通常会监听消息目的地(队列或主题),当有新消息到达时,会根据不同的消息模型(点对点或发布/订阅)接收消息。在点对点模型中,每个消息只能被一个消费者接收;在发布/订阅模型中,消息可以被多个订阅者接收。同时,消费者可以通过消息选择器来过滤消息,只接收符合特定条件的消息。例如,在使用点对点模型的消息过滤方法时,可创建一个未送达消息消费者,其消息选择器是该队列所有消费者的所有消息选择器的并集的精确否定,以确保未被其他消费者接收的消息仍能被处理[^4]。 ### 最佳实践 - **并发控制**:合理设置并发消费者的数量,以提高消息处理的效率,但要避免过多的并发导致资源竞争和性能下降。 - **事务处理**:在处理消息时,使用事务可以确保消息的原子性,即要么所有消息处理成功,要么全部失败回滚。 - **消息选择器的使用**:根据业务需求合理使用消息选择器,过滤不必要的消息,减少消费者的处理负担。 - **错误处理和重试机制**:在消息处理失败时,要有相应的错误处理和重试机制,确保消息最终能被正确处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值