JMS之ActiveMQ工具类

为什么要用MQ

网络上面说使用jms的好处,肯定一搜就一大堆。以下是我自己的几个观点
1、代码解耦,使得各个模块的耦合度降低
2、消除高并发访问高峰,如商城系统
3、分布式服务之间的交互,保证消息不会丢失以及逻辑顺序一致性

ActiveMq环境搭建

一、准备好java环境(这个搭建教程就直接忽略)
二、下载对应版本的ActiveMq 下载地址
三、解压安装

#创建目录 /opt/activemq
$ mkdir /opt/activemq

# 把下载好的activemq安装包放到/opt/activemq目录下
$ rz -bey

# 解压
$ tar -zxf apache-activemq-5.15.13-bin.tar.gz

#到解压好的文件夹下
cd /opt/activemq/apache-activemq-5.15.13

#启动
$ ./bin/activemq start

# 关闭
$ ./bin/activemq stop

四、登录管理平台
http://<your-host-ip>:8161
登录账户以及密码 默认都是admin
如果不正确,默认账号密码在conf/user.properties中

管理账号

新增测试账号
修改conf/activemq.xml文件
在 broker中添加

        <plugins>
            <simpleAuthenticationPlugin>
                <users>
                    <authenticationUser username="tricky" password="123456" groups="users,admins"/>
                </users>
            </simpleAuthenticationPlugin>
        </plugins>

如我这里是添加一个账号为 tricky 密码为 123456 的账号。其属于users&admins组别
在这里添加了之后,就可以使得程序里面只能用该账号来连接activemq服务(也就是连接 tcp://<your-host-ip>:61616)

ActiveMQ工具类

项目下载地址 https://download.csdn.net/download/sail331x/12588151
maven引用

		<dependency>
            <groupId>javax.jms</groupId>
            <artifactId>javax.jms-api</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!--ActiveMq-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
            <version>1.5.0.RELEASE</version>
        </dependency>
        <!--消息队列连接池-->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-pool</artifactId>
            <version>5.15.0</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>jakarta.persistence</groupId>
            <artifactId>jakarta.persistence-api</artifactId>
            <version>2.2.3</version>
            <scope>compile</scope>
        </dependency>

JActiveMqSerivce类,这个类主要是提供外部调用


import com.tricky.blog.mq.activemq.core.spring.AbstractActiveMqConsumerHandler;
import org.apache.activemq.jms.pool.PooledConnectionFactory;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.*;
import java.io.Serializable;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * active-mq service工具处理<br/>
 *
 * @Autor Tricky
 * @Date 2020-05-28 17:11:11
 */
public class JActiveMqService {
	private static Logger LOGGER = LoggerFactory.getLogger(JActiveMqService.class);
	private PooledConnectionFactory pooledConnectionFactory;
	/**
	 * topic消费者
	 */
	private Map<String, MessageConsumer> topicConsumersMap = new ConcurrentHashMap<>();
	/**
	 * queue消费者
	 */
	private Map<String, MessageConsumer> queueConsumersMap = new ConcurrentHashMap<>();

	/**
	 * topic生产者的连接
	 */
	private TopicConnection topicProducerConnection;

	/**
	 * queue生产者
	 */
	private QueueConnection queueProducerConnection;


	public JActiveMqService(ActiveMQConfig config) {
		try {
			pooledConnectionFactory = ActiveMQUtils.createPoolConnectionFactory(config);
			topicProducerConnection = pooledConnectionFactory.createTopicConnection();
			topicProducerConnection.start();
			queueProducerConnection = pooledConnectionFactory.createQueueConnection();
			queueProducerConnection.start();
		} catch (Throwable t) {
			LOGGER.error(t.getMessage(), t);
			throw new RuntimeException("初始化ActiveMQ失败");
		}
	}

	public Connection getConnection() throws JMSException {
		return pooledConnectionFactory.createConnection();
	}


	/**
	 * 创建session
	 *
	 * @param connection
	 * @return
	 * @throws JMSException
	 */
	public Session createSession(Connection connection) throws JMSException {
		return ActiveMQUtils.createSessionByAcknowledgeType(connection, Session.AUTO_ACKNOWLEDGE);
	}


	/**
	 * 关闭连接
	 *
	 * @param connection
	 * @param session
	 */
	public void close(Connection connection, Session session) {
		try {
			if (session != null) {
				session.close();
			}
		} catch (Throwable t) {
			LOGGER.error(t.getMessage(), t);
		}

		try {
			if (connection != null) {
				connection.close();
			}
		} catch (Throwable t) {
			LOGGER.error(t.getMessage(), t);
		}
	}

	/**
	 * 以发布订阅模式发送消息,这里用默认的topic名字 {@link AbstractActiveMqConsumerHandler#DEFAULT_TOPIC_NAME}
	 *
	 * @param msg
	 * @param <T>
	 * @throws JMSException
	 */
	public <T extends Serializable> void sendTopicMessage(T msg) throws JMSException {
		this.sendTopicMessage(AbstractActiveMqConsumerHandler.DEFAULT_TOPIC_NAME, msg);
	}

	/**
	 * 以发布订阅模式发送消息
	 *
	 * @param topicName
	 * @param msg
	 * @param <T>
	 * @throws JMSException
	 */
	public <T extends Serializable> void sendTopicMessage(String topicName, T msg) throws JMSException {
		Objects.requireNonNull(topicName, "Topic名字不可为空");
		Objects.requireNonNull(msg);
		TopicConnection conn = pooledConnectionFactory.createTopicConnection();
		Session session = createSession(conn);
		Topic topic = ActiveMQUtils.createTopic(session, topicName);
		MessageProducer messageProducer = ActiveMQUtils.createMessageProducer(session, topic);
		ObjectMessage send = session.createObjectMessage(msg);
		messageProducer.send(send);
		close(conn, session);
	}

	/**
	 * 以发布订阅模式发送消息
	 *
	 * @param topicName
	 * @param text
	 * @throws JMSException
	 */
	public void sendTopicTextMessage(String topicName, String text) throws JMSException {
		TopicConnection conn = pooledConnectionFactory.createTopicConnection();
		Session session = createSession(conn);
		Topic topic = ActiveMQUtils.createTopic(session, topicName);
		MessageProducer messageProducer = ActiveMQUtils.createMessageProducer(session, topic);
//		ObjectMessage send = session.createObjectMessage(msg);
		TextMessage send = session.createTextMessage(text);
		messageProducer.send(send);
		close(conn, session);
	}


	/**
	 * 以点对点/Queue模式发送消息
	 *
	 * @param queueName
	 * @param msg
	 * @param <T>
	 * @throws JMSException
	 */
	public <T extends Serializable> void sendQueueMessage(String queueName, T msg) throws JMSException {
		QueueConnection conn = pooledConnectionFactory.createQueueConnection();
		Session session = createSession(conn);
		Queue queue = ActiveMQUtils.createQueue(session, queueName);
		MessageProducer messageProducer = ActiveMQUtils.createMessageProducer(session, queue);
		ObjectMessage send = session.createObjectMessage(msg);
		messageProducer.send(send);
		close(conn, session);
	}

	/**
	 * queue发送text消息
	 *
	 * @param queueName
	 * @param text
	 * @throws JMSException
	 */
	public void sendQueueTextMessage(String queueName, String text) throws JMSException {
		QueueConnection conn = pooledConnectionFactory.createQueueConnection();
		Session session = createSession(conn);
		Queue queue = ActiveMQUtils.createQueue(session, queueName);
		MessageProducer messageProducer = ActiveMQUtils.createMessageProducer(session, queue);
		TextMessage send = session.createTextMessage(text);
		messageProducer.send(send);
		close(conn, session);
	}

	/**
	 * queue,对于同groupName的消息会按照顺序执行(而且在只能在某个节点执行)
	 *
	 * @param queueName
	 * @param msg
	 * @param <T>
	 * @throws JMSException
	 */
	public <T extends Serializable> void sendQueueMessageOfGroups(String queueName, String groupName, T msg) throws JMSException {
		if (StringUtils.isEmpty(queueName)) {
			throw new IllegalArgumentException("GroupName不可为空");
		}
		QueueConnection conn = pooledConnectionFactory.createQueueConnection();
		Session session = createSession(conn);
		Queue queue = ActiveMQUtils.createQueue(session, queueName);
		MessageProducer messageProducer = ActiveMQUtils.createMessageProducer(session, queue);
		ObjectMessage send = session.createObjectMessage(msg);
		send.setStringProperty("JMSXGroupID", groupName);
		messageProducer.send(send);
		close(conn, session);
	}

	/**
	 * 发送text消息
	 *
	 * @param queueName
	 * @param groupName
	 * @param text
	 * @throws JMSException
	 */
	public void sendQueueTextMessageOfGroups(String queueName, String groupName, String text) throws JMSException {
		if (StringUtils.isEmpty(queueName)) {
			throw new IllegalArgumentException("GroupName不可为空");
		}
		QueueConnection conn = pooledConnectionFactory.createQueueConnection();
		Session session = createSession(conn);
		Queue queue = ActiveMQUtils.createQueue(session, queueName);
		MessageProducer messageProducer = ActiveMQUtils.createMessageProducer(session, queue);
		TextMessage send = session.createTextMessage(text);
		send.setStringProperty("JMSXGroupID", groupName);
		messageProducer.send(send);
		close(conn, session);
	}

	/**
	 * 启动Topic消费者
	 *
	 * @param topicName 主题名称
	 */
	public synchronized MessageConsumer startTopicConsumer(String topicName, ConsumerMsgHandler handler) throws JMSException {
		MessageConsumer consumer = topicConsumersMap.get(topicName);
		if (consumer != null) {
			LOGGER.error(String.format("重复启动Topic消费者[%s]", topicName));
			return consumer;
		}
		return ActiveMQUtils.createTopicConsumer(topicProducerConnection, topicName, handler);
	}


	/**
	 * 启动Topic消费者
	 *
	 * @param topicName 主题名称
	 */
	public synchronized MessageConsumer startQueueConsumer(String topicName, ConsumerMsgHandler handler) throws JMSException {
		MessageConsumer consumer = queueConsumersMap.get(topicName);
		if (consumer != null) {
			LOGGER.error(String.format("重复启动Queue消费者[%s]", topicName));
			return consumer;
		}
		return ActiveMQUtils.createQueueConsumer(queueProducerConnection, topicName, handler);
	}


	/**
	 * 关闭一个topic的consumer
	 *
	 * @param topicName
	 * @return
	 * @throws JMSException
	 */
	public boolean closeTopicConsumer(String topicName) throws JMSException {
		MessageConsumer consumer = topicConsumersMap.get(topicName);
		if (consumer != null) {
			try {
				consumer.close();
				topicConsumersMap.remove(topicName);
				return true;
			} catch (Throwable t) {
				LOGGER.error(t.getMessage(), t);
				return false;
			}
		}
		LOGGER.error(String.format("获取对应的Topic[%s]的Consumer不存在", topicName));
		return false;
	}


	/**
	 * 关闭一个topic的consumer
	 *
	 * @param topicName
	 * @return
	 * @throws JMSException
	 */
	public boolean closeQueueConsumer(String topicName) throws JMSException {
		MessageConsumer consumer = queueConsumersMap.get(topicName);
		if (consumer != null) {
			try {
				consumer.close();
				queueConsumersMap.remove(topicName);
				return true;
			} catch (Throwable t) {
				LOGGER.error(t.getMessage(), t);
				return false;
			}
		}
		LOGGER.error(String.format("获取对应的Queue[%s]的Consumer不存在", topicName));
		return false;
	}
}

ActiveMQUtils 操作类 这个是给JActiveMqService调用


/**
 * active-mq 操作
 *
 * @Autor Tricky
 * @Date 2020-05-27 18:38:24
 */
public abstract class ActiveMQUtils {

	private static Logger LOGGER = LoggerFactory.getLogger(ActiveMQUtils.class);

	/**
	 * 关闭连接
	 *
	 * @param connection
	 * @throws JMSException
	 */
	public static void close(Connection connection) throws JMSException {
		if (connection != null) {
			connection.close();
		}
	}

	/**
	 * 关闭会话
	 *
	 * @param session
	 * @throws JMSException
	 */
	public static void close(Session session) throws JMSException {
		if (session != null) {
			session.close();
		}
	}

	public static PooledConnectionFactory createPoolConnectionFactory(ActiveMQConfig config) {
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(config.getUser(), config.getPassword(), config.getBrokerUrl());
		factory.setCloseTimeout(config.getCloseTimeout());
		factory.setNonBlockingRedelivery(config.isNonBlockingRedelivery());
		factory.setSendTimeout(config.getSendTimeout());
		factory.setTrustAllPackages(config.isTrustAllPackage());
		if (!config.isTrustAllPackage()) {
			factory.setTrustedPackages(config.getTrustPackages());
		}
		PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory();
		pooledConnectionFactory.setMaxConnections(config.getMaxConnections());
		pooledConnectionFactory.setMaximumActiveSessionPerConnection(config.getMaxActiveSession());
		pooledConnectionFactory.setIdleTimeout(config.getIdleTimeout());
		/**
		 * 异常重连
		 */
		pooledConnectionFactory.setReconnectOnException(true);
		pooledConnectionFactory.setConnectionFactory(factory);
		return pooledConnectionFactory;
	}

	/**
	 * 创建连接
	 *
	 * @param factory 连接池工厂
	 * @return
	 * @throws JMSException
	 */
	public static Connection createConnection(PooledConnectionFactory factory) throws JMSException {


		Connection conn = factory.createConnection();
		conn.start();
		return conn;
	}


	/**
	 * 建立会话
	 *
	 * @param connection
	 * @param transacted      是否开启事务 true为开启事务
	 * @param acknowledgeMode 值 {@link Session#AUTO_ACKNOWLEDGE} 自动确认<br/>
	 *                        值 {@link Session#CLIENT_ACKNOWLEDGE} 客户端确认<br/>
	 * @return
	 * @throws JMSException
	 */
	public static Session createSession(Connection connection, boolean transacted, int acknowledgeMode) throws JMSException {
		return connection.createSession(transacted, acknowledgeMode);
	}

	/**
	 * 建立事务session,提交跟处理需要自己调用 session.commit()
	 *
	 * @param connection
	 * @return
	 * @throws JMSException
	 */
	public static Session createTransactedSession(Connection connection) throws JMSException {
		return connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
	}

	/**
	 * 建立自动commit的session
	 *
	 * @param connection
	 * @param acknowledgeType 值{@link Session#AUTO_ACKNOWLEDGE} 自动确认消息<br/>
	 *                        值{@link Session#CLIENT_ACKNOWLEDGE} 客户端确认消息<br/>
	 *                        值{@link Session#DUPS_OK_ACKNOWLEDGE} 消息可重复确认<br/>
	 *                        值{@link Session#SESSION_TRANSACTED} Session启用事务<br/>
	 * @return
	 * @throws JMSException
	 */
	public static Session createSessionByAcknowledgeType(Connection connection, int acknowledgeType) throws JMSException {
		return connection.createSession(false, acknowledgeType);
	}

	/**
	 * 创建一个主题
	 *
	 * @param session
	 * @param topicName
	 * @return
	 * @throws JMSException
	 */
	public static Topic createTopic(Session session, String topicName) throws JMSException {
		return session.createTopic(topicName);
	}


	/**
	 * 创建一个queue
	 *
	 * @param session
	 * @param queueName
	 * @return
	 * @throws JMSException
	 */
	public static Queue createQueue(Session session, String queueName) throws JMSException {
		return session.createQueue(queueName);
	}


	/**
	 * 创建一个生产者
	 *
	 * @param session     会话
	 * @param destination topic or queue
	 * @return
	 * @throws JMSException
	 */
	public static MessageProducer createProducer(Session session, Destination destination) throws JMSException {
		return session.createProducer(destination);
	}

	/**
	 * 创建p2p/队列模式消费者,并启用监听
	 *
	 * @param poolFactory
	 * @param queueName
	 * @param handler
	 * @throws JMSException
	 */
	public static MessageConsumer createQueueConsumer(PooledConnectionFactory poolFactory, String queueName, ConsumerMsgHandler handler) throws JMSException {
		Connection conn = createConnection(poolFactory);
		return createQueueConsumer(conn, queueName, handler);
	}


	/**
	 * 创建queue消费者
	 *
	 * @param conn
	 * @param queueName
	 * @param handler
	 * @throws JMSException
	 */
	public static MessageConsumer createQueueConsumer(Connection conn, String queueName, ConsumerMsgHandler handler) throws JMSException {
		Session session = createSessionByAcknowledgeType(conn, Session.AUTO_ACKNOWLEDGE);
		return createQueueConsumer(session, queueName, handler);
	}

	/**
	 * 创建queue消费者
	 *
	 * @param session
	 * @param queueName
	 * @param handler
	 * @throws JMSException
	 */
	public static MessageConsumer createQueueConsumer(Session session, String queueName, ConsumerMsgHandler handler) throws JMSException {
		Queue queue = createQueue(session, queueName);
		return createConsumer(session, queue, handler);
	}

	/**
	 * 创建发布订阅/Topic模式消费者,并启用监听
	 *
	 * @param factory
	 * @param topicName
	 * @param handler
	 * @throws JMSException
	 */
	public static MessageConsumer createTopicConsumer(PooledConnectionFactory factory, String topicName, ConsumerMsgHandler handler) throws JMSException {
		Connection conn = createConnection(factory);
		return createTopicConsumer(conn, topicName, handler);
	}


	/**
	 * 创建topic消费者
	 *
	 * @param conn
	 * @param topicName
	 * @param handler
	 * @throws JMSException
	 */
	public static MessageConsumer createTopicConsumer(Connection conn, String topicName, ConsumerMsgHandler handler) throws JMSException {
		Session session = createSessionByAcknowledgeType(conn, Session.AUTO_ACKNOWLEDGE);
		return createTopicConsumer(session, topicName, handler);
	}

	/**
	 * 创建topic消费者
	 *
	 * @param session
	 * @param topicName
	 * @param handler
	 * @throws JMSException
	 */
	public static MessageConsumer createTopicConsumer(Session session, String topicName, ConsumerMsgHandler handler) throws JMSException {
		Topic topic = createTopic(session, topicName);
		return createConsumer(session, topic, handler);
	}

	/**
	 * 根据destination创建消费者
	 *
	 * @param session
	 * @param destination
	 * @param handler
	 * @throws JMSException
	 */
	public static MessageConsumer createConsumer(Session session, Destination destination, ConsumerMsgHandler handler) throws JMSException {
		MessageConsumer consumer = session.createConsumer(destination);
		consumer.setMessageListener((msg) -> {
			try {
				try {
					handler.onMessage(msg);
				} catch (Throwable t) {
					LOGGER.error(t.getMessage(), t);
				}
			} catch (Throwable t) {
				LOGGER.error(t.getMessage(), t);
			}
		});
		return consumer;
	}

	public static MessageProducer createQueueMessageProducer(PooledConnectionFactory factory, String queueName) throws JMSException {
		Connection connection = createConnection(factory);
		return createQueueMessageProducer(connection, queueName);
	}

	public static MessageProducer createTopicMessageProducer(PooledConnectionFactory factory, String topicName) throws JMSException {
		Connection connection = createConnection(factory);
		return createTopicMessageProducer(connection, topicName);
	}


	public static MessageProducer createQueueMessageProducer(Connection connection, String queueName) throws JMSException {
		Session se = createSessionByAcknowledgeType(connection, Session.AUTO_ACKNOWLEDGE);
		return createQueueMessageProducer(se, queueName);
	}

	public static MessageProducer createTopicMessageProducer(Connection connection, String topicName) throws JMSException {
		Session se = createSessionByAcknowledgeType(connection, Session.AUTO_ACKNOWLEDGE);
		return createTopicMessageProducer(se, topicName);
	}

	public static MessageProducer createQueueMessageProducer(Session session, String queueName) throws JMSException {
		return createMessageProducer(session, session.createQueue(queueName));
	}

	public static MessageProducer createTopicMessageProducer(Session session, String topicName) throws JMSException {
		return createMessageProducer(session, session.createTopic(topicName));
	}


	public static MessageProducer createMessageProducer(Session session, Destination destination) throws JMSException {
		return session.createProducer(destination);
	}


	/**
	 * 发送消息
	 *
	 * @param session
	 * @param producer
	 * @param message
	 * @throws JMSException
	 */
	public static void sendMessage(Session session, MessageProducer producer, Message message) throws JMSException {
		producer.send(message);
		session.commit();
	}

}

AbstractActiveMqConsumerHandler类【消费者定义】
说明:消费者类定义分为Topic消息Consumer以及Queue消息Consumer,查看该类的带参构造方法即可。
消息处理:消息处理方法如下,其中MqMessageHandler表示该方法为一个消息处理的方法。

	@MqMessageHandler
	private void onDemoTopicMsg(TopicMsgDefined.DemoTopicMsg msg) {
		System.out.println(getClass().getSimpleName() + "收到Topic消息:" + msg.toString());
	}

/**
 * mq消费者处理
 *
 * @Autor Tricky
 * @Date 2020-06-03 10:00:03
 */
public abstract class AbstractActiveMqConsumerHandler {
	protected static Logger LOGGER = LoggerFactory.getLogger(AbstractActiveMqConsumerHandler.class);
	public static final String DEFAULT_TOPIC_NAME = "DefaultTopicName";
	/**
	 * queue消息
	 */
	public static final byte CONSUMER_TYPE_QUEUE = 1;

	/**
	 * topic消息
	 */
	public static final byte CONSUMER_TYPE_TOPIC = 2;
	/**
	 * 消息名称
	 */
	protected final String name;
	protected final byte consumeType;
	@Autowired
	protected JActiveMqService mqService;

	protected Map<Class<?>, List<Method>> onMessageList;

	/**
	 * @param name        消费的消息名称
	 * @param consumeType 消息类型<br/>
	 *                    值 {@link #CONSUMER_TYPE_QUEUE} queue消息<br/>
	 *                    值 {@link #CONSUMER_TYPE_TOPIC} topic消息<br/>
	 *                    值 其它 初始化报异常
	 */
	protected AbstractActiveMqConsumerHandler(String name, byte consumeType) {
		this.name = name;
		this.consumeType = consumeType;
	}

	/**
	 * queue类型
	 *
	 * @param queueName queue名字
	 */
	public AbstractActiveMqConsumerHandler(String queueName) {
		this(queueName, CONSUMER_TYPE_QUEUE);
	}

	/**
	 * topic类型,topic采用默认类型
	 */
	public AbstractActiveMqConsumerHandler() {
		this(DEFAULT_TOPIC_NAME, CONSUMER_TYPE_TOPIC);
	}

	@PostConstruct
	private void init() throws JMSException {
		if (this.consumeType == CONSUMER_TYPE_QUEUE) {
			mqService.startQueueConsumer(name, this::onMessage);
		} else if (this.consumeType == CONSUMER_TYPE_TOPIC) {
			mqService.startTopicConsumer(name, this::onMessage);
		} else {
			throw new IllegalArgumentException("未识别的consumeType类型:" + this.consumeType);
		}

		Class<?> clazz = this.getClass();
		ConcurrentHashMap<Class<?>, List<Method>> mapList = new ConcurrentHashMap<>();
		while (clazz != AbstractActiveMqConsumerHandler.class) {
			Method[] methods = clazz.getDeclaredMethods();
			for (Method e : methods) {
				MqMessageHandler anno = e.getAnnotation(MqMessageHandler.class);
				if (anno != null) {
					Class<?>[] types = e.getParameterTypes();
					if (types.length != 1 || (!Serializable.class.isAssignableFrom(types[0]))) {
						LOGGER.error(String.format("注册Mq消息监听失败 %s.%s 参数必须只能有一个 且为%s的子类", clazz.getName(), e.getName(), Serializable.class.getName()));
						continue;
					}
					List<Method> list = mapList.computeIfAbsent(types[0], (k) -> new ArrayList<>());
					e.setAccessible(true);
					list.add(e);
				}
			}

			clazz = clazz.getSuperclass();
		}
		onMessageList = Collections.unmodifiableMap(mapList);

	}

	public final void onMessage(Message message) {
		try {
			if (message instanceof ObjectMessage) {
				this.onObjectMessage(((ObjectMessage) message).getObject());
			} else if (message instanceof TextMessage) {
				this.onTextMessage(((TextMessage) message));
			}
		} catch (Throwable t) {
			LOGGER.error(String.format("消费消息异常:name=%s type=%d clazz=%s", name, consumeType, message.getClass().getName()));
		}
	}

	/**
	 * 收到text消息处理
	 *
	 * @param message
	 */
	protected abstract void onTextMessage(TextMessage message) throws JMSException;

	/**
	 * object消息处理
	 *
	 * @param obj
	 */
	private void onObjectMessage(Object obj) {
		List<Method> methods = onMessageList.get(obj.getClass());
		if (methods == null || methods.size() <= 0) {
			LOGGER.error(String.format("未识别的MQ消息类型:%s name=%s consumeType=%d", obj.getClass().getName(), name, consumeType));
		} else {
			for (Method e : methods) {
				try {
					e.invoke(this, obj);
				} catch (Throwable t) {
					LOGGER.error(t.getMessage(), t);
				}
			}
		}
	}
}

配置类 ActiveMQConfig


/**
 * 配置信息
 *
 * @Autor Tricky
 * @Date 2020-05-28 11:13:18
 */
@Getter
@Setter
public class ActiveMQConfig {
	/**
	 * 连接用户名
	 */
	private String user = "admin";
	/**
	 * 连接使用密码
	 */
	private String password = "admin";
	/**
	 * 连接地址
	 */
	private String brokerUrl = "tcp://127.0.0.1:61616";
	/**
	 * 结束之前等待的时间 毫秒
	 */
	private int closeTimeout = 15000;
	/**
	 * 是否在回滚回滚消息之前停止消息传递。这意味着当启用此命令时,消息顺序不会被保留。
	 * 默认 false
	 */
	private boolean nonBlockingRedelivery;
	/**
	 * 发送超时,毫秒
	 * 默认0 不会超时
	 */
	private int sendTimeout = 0;

	/**
	 * 连接池最大连接数量
	 */
	private int maxConnections = 32;

	/**
	 * 空闲连接过期 毫秒
	 */
	private int idleTimeout = 600000;

	/**
	 * 每隔会话最大的同时存在session
	 */
	private int maxActiveSession = 300;

	/**
	 * ObjectMessage的时候是否信任所有的package
	 */
	private boolean trustAllPackage = false;

	/**
	 * 可信任的包,当trustAllPackage为false的时候使用
	 */
	private List<String> trustPackages;
}

项目的下载位置为 https://download.csdn.net/download/sail331x/12588151
项目我自己运行过,demo也跑过,确认没问题

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值