最近学到消息队列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你就在控制台看到希望看到的内容了。
希望对大家有帮助。