JMS消息队列之ActiveMQ

本文介绍如何通过Java消息服务(JMS)与Apache ActivemQ实现消息队列的发送与接收。首先安装并配置了ActivemQ服务,然后通过两个核心类ConsumerTools和ProducerTools演示了消息的注入和拿取过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近学到消息队列JMS,所以写个博客记录一下。

环境这里我就不介绍了,我用的windows,并且安装了activemq的包,没有的可以自己去下载安装。然后修改包里的配置,目录在:D:\Softwares\apache-activemq-5.12.1\conf\activemq.xml,修改其中如下所示的代码:

  <transportConnectors>
            <!-- DOS protection, limit concurrent connections to 1000 and frame size to 100MB -->
            <transportConnector name="openwire" uri="tcp://localhost:61616?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="ssl" uri="ssl://localhost:61617?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="stomp" uri="stomp://localhost:61613?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
            <transportConnector  uri="http://localhost:8081?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
            <transportConnector  uri="udp://localhost:61618?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
        </transportConnectors>
然后去bin目录下启动activemq即可,启动后用浏览器登录地址:

http://localhost:8161/admin/ 账号密码都是:admin,登录即可看到页面,证明安装成功。那么我们在eclipse中创建项目进行消息队列的注入和拿取。

我有两个主要的类分别为:ConsumerTools(拿取者)和ProducerTools(注入者),和各自的启动类ConsumerTest与ProducerTest:

package com.activeMQ;

import javax.jms.Connection;

import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * 
 * @author 马慧超
 *
 */
public class ConsumerTools implements MessageListener, ExceptionListener {
	private String user = ActiveMQConnection.DEFAULT_USER;
	private String password = ActiveMQConnection.DEFAULT_PASSWORD;
	private String url = ActiveMQConnection.DEFAULT_BROKER_URL;
	ActiveMQConnectionFactory factory = null;
	Connection conn = null;
	Session session = null;

	Destination destination = null;
	MessageConsumer consumer = null;
	public static Boolean isconnection = false;

	/**
	 * 初始化
	 * 
	 * @throws Exception
	 */
	public void init() throws Exception {
		factory = new ActiveMQConnectionFactory(user, password, url);
		conn = factory.createConnection();
		session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
		destination = session.createQueue("myqueue");
		consumer = session.createConsumer(destination);
	}

	/**
	 * 消费
	 * 
	 * @throws Exception
	 */
	public void consumeMessage() throws Exception {

		init(); // 执行初始化操作(也就是进行参数赋值)
		conn.start(); // 开始连接

		consumer.setMessageListener(this);
		conn.setExceptionListener(this);
		Thread.sleep(2000);
		System.out.println("Consumer:->Begin Listening");
		isconnection = true;
		/**
		 * 这里需要注意,如下方法和上面的setExceptionListener不要同时使用,会报错。
		 */
		// Message message = consumer.receive();
		// System.out.println(message.getJMSMessageID());
	}

	// 关闭连接
	public void close() throws JMSException {
		System.out.println("Consumer:->Closing connection");
		if (consumer != null)
			consumer.close();
		if (session != null)
			session.close();
		if (conn != null)
			conn.close();
	}

	@Override
	public void onMessage(Message message) {
		try {
			if (message instanceof TextMessage) {
				TextMessage tm = (TextMessage) message;
				String msg = tm.getText();
				System.out.println("Consumer get message: " + msg);
			} else {
				System.out.println("Consumer get message: " + message);
			}

		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onException(JMSException arg0) {
		// TODO Auto-generated method stub
		isconnection = false;
	}

}
package com.activeMQ;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 
 * @author 马慧超
 *
 */
public class ProducerTools {
	private static String user = ActiveMQConnection.DEFAULT_USER;
	private static String password = ActiveMQConnection.DEFAULT_PASSWORD;
	private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;

	ActiveMQConnectionFactory factory = null;
	Connection conn = null;
	Destination destination = null;
	Session session = null;
	MessageProducer producer = null;

	/**
	 * 初始化
	 * 
	 * @throws Exception
	 */
	public void init() throws Exception {
		factory = new ActiveMQConnectionFactory(user, password, url);
		conn = factory.createConnection();
		session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
		destination = session.createQueue("myqueue");
		producer = session.createProducer(destination);
		producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
	}

	/**
	 * 生产
	 * 
	 * @throws Exception
	 */
	public void producePro(String message) throws Exception {
		init(); // 初始化
		TextMessage msg = session.createTextMessage(message); // textmessage是继承message的
		System.out.println("Producer:->Sending message: " + message);
		producer.send(msg); // 发送文本
		System.out.println("Producer:->Message sent complete!");
	}

	public void close() throws JMSException {
		System.out.println("Producer:->Closing connection");
		if (producer != null) {
			producer.close();
		}
		if (session != null) {
			session.close();
		}
		if (conn != null) {
			conn.close();
		}

	}
}
package com.activeMQ;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ProducerTest {
	public static void main(String[] args) throws Exception {
		ProducerTools producer = new ProducerTools();
		producer.producePro("I am the product that be created");
		producer.close();
	}
}
package com.activeMQ;

public class ConsumerTest implements Runnable {
	static Thread t1;

	public static void main(String[] args) throws InterruptedException {
		t1 = new Thread(new ConsumerTest());
		t1.start();
		while (true) {
			if (!t1.isAlive()) { // 如果t1线程死了
				t1 = new Thread(new ConsumerTest()); // 再起一个
				t1.start();
			}
			Thread.sleep(5000);
		}
	}

	@Override
	public void run() {
		try {
			ConsumerTools consumer = new ConsumerTools();
			consumer.consumeMessage();
			while (consumer.isconnection) {
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
启动的时候先启动ProducerTest,然后你会在浏览器上看到queue列里有你注入的消息(没有的话刷新),然后再启动ConsumerTest你就在控制台看到希望看到的内容了。

希望对大家有帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值