本人博客开始迁移,博客整个架构自己搭建及编码 http://www.cookqq.com/listBlog.action
《ActiveMQ发消息和收消息》详细介绍了ActiveMQ发消息和收消息,消息保存在消息队列(queue)中,消息队列数据保存在计算机内存中,假如ActiveMQ服务器由于某些原因突然停止,那消息队列中内容还在吗?用事实说话吧,把ActiveMQ服务器停止,然后再看看ActiveMQ页面上的队列信息queue,如图:
activemq_queue队列中的信息全部丢失了。为了解决这个问题,可以把队列数据持久化,分为文件持久化和数据库持久化。
现在详细分析文件持久化。直接来代码吧:
消息发送者:
package com.activemq.queue;
import javax.jms.Connection;
public class Sender {
private static final int SEND_NUMBER = 1;
public static void main(String[] args) {
// ConnectionFactory 接口(连接工厂) 用户用来创建到JMS提供者的连接的被管对象。
// JMS客户通过可移植的接口访问连接,这样当下层的实现改变时,代码不需要进行修改。
// 管理员在JNDI名字空间中配置连接工厂,这样,JMS客户才能够查找到它们。
// 根据消息类型的不同,用户将使用队列连接工厂,或者主题连接工厂。
ConnectionFactory connectionFactory;
// Connection :JMS 客户端到JMS Provider 的连接
// Connection 接口(连接) 连接代表了应用程序和消息服务器之间的通信链路。
// 在获得了连接工厂后,就可以创建一个与JMS提供者的连接。根据不同的连接类型,
// 连接允许用户创建会话,以发送和接收队列和主题到目标。
Connection connection = null;
// Session: 一个发送或接收消息的线程
// Session 接口(会话) 表示一个单线程的上下文,用于发送和接收消息。
// 由于会话是单线程的,所以消息是连续的,就是说消息是按照发送的顺序一个一个接收的。
// 会话的好处是它支持事务。如果用户选择了事务支持,会话上下文将保存一组消息,直到事务被提交才发送这些消息。
// 在提交事务之前,用户可以使用回滚操作取消这些消息。一个会话允许用户创建消息生产者来发送消息,创建消息消费者来接收消息。
Session session;
// Destination :消息的目的地;消息发送给谁.
// Destination 接口(目标) 目标是一个包装了消息目标标识符的被管对象,
// 消息目标是指消息发布和接收的地点,或者是队列,或者是主题。
// JMS管理员创建这些对象,然后用户通过JNDI发现它们。
// 和连接工厂一样,管理员可以创建两种类型的目标,点对点模型的队列,以及发布者/订阅者模型的主题。
Destination destination;
// MessageProducer:消息发送者
// MessageProducer 接口(消息生产者) 由会话创建的对象,用于发送消息到目标。
// 用户可以创建某个目标的发送者,也可以创建一个通用的发送者,在发送消息时指定目标。
MessageProducer producer;
// TextMessage message;
// 构造ConnectionFactory实例对象,此处采用ActiveMq的实现jar
connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_USER, //null
ActiveMQConnection.DEFAULT_PASSWORD, //null
"tcp://localhost:61616");
try {
// 构造从工厂得到连接对象
connection = connectionFactory.createConnection();
// 启动
connection.start();
// 获取操作连接
session = connection.createSession(Boolean.TRUE,
Session.AUTO_ACKNOWLEDGE); //1
destination = session.createQueue(RunServer.queueName);
// 得到消息生成者【发送者】
producer = session.createProducer(destination);
// 设置不持久化,可以更改
producer.setDeliveryMode(DeliveryMode.PERSISTENT); //2
// 构造消息
sendMessage(session, producer);
session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != connection)
connection.close();
} catch (Throwable ignore) {
}
}
}
public static void sendMessage(Session session, MessageProducer producer)
throws Exception {
for (int i = 1; i <= SEND_NUMBER; i++) {
TextMessage message = session
.createTextMessage("ActiveMq 发送的消息" + i);
// 发送消息到目的地方
System.out.println("发送消息:" + i);
producer.send(message);
}
}
}
消息接受者:
package com.activemq.queue;
import javax.jms.Connection;
public class Receiver {
public static void main(String[] args) {
// ConnectionFactory :连接工厂,JMS 用它创建连接
ConnectionFactory connectionFactory;
// Connection :JMS 客户端到JMS Provider 的连接
Connection connection = null;
// Session: 一个发送或接收消息的线程
final Session session;
// Destination :消息的目的地;消息发送给谁.
Destination destination;
// 消费者,消息接收者
// MessageConsumer 接口(消息消费者) 由会话创建的对象,用于接收发送到目标的消息。
// 消费者可以同步地(阻塞模式),或异步(非阻塞)接收队列和主题类型的消息。
MessageConsumer consumer;
connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_USER,
ActiveMQConnection.DEFAULT_PASSWORD,
"tcp://localhost:61616");
try {
// 构造从工厂得到连接对象
connection = connectionFactory.createConnection();
// 启动
connection.start();
// 获取操作连接
session = connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
//queue_name跟sender的保持一致,一个创建一个来接收
destination = session.createQueue(RunServer.queueName);
consumer = session.createConsumer(destination);
// //第一种情况
// int i = 0;
// while (i < 3) {
// i++;
// TextMessage message = (TextMessage) consumer.receive();
// session.commit();
// // TODO something....
// System.out
// .println("收到消息:" +message.getText());
// }
// session.close();
// connection.close();
//----------------第一种情况结束----------------------
// 第二种方式
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message arg0) {
if(arg0 instanceof TextMessage){
try {
System.out.println("arg0="+((TextMessage)arg0).getText());
session.commit();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
//第三种情况
// while (true) {
// Message msg = consumer.receive(1000);
// TextMessage message = (TextMessage) msg;
// if (null != message) {
// System.out.println("收到消息:" + message.getText());
// }
// }
} catch (Exception e) {
e.printStackTrace();
}
}
}
程序中启动activemq服务:
package com.activemq.queue;
import java.io.File;
public class RunServer {
public static String jmxDomain = "jms-broker";
public static int connectorPort = 2011;
public static String connectorPath = "/jmxrmi";
public static String queueName = "activemq_queue";
/** 启动activeMQ服务 */
public static void main(String[] args) throws Exception {
// java代码调用activemq相关的类来构造并启动brokerService
BrokerService broker = new BrokerService();
// 以下是持久化的配置
// 持久化文件存储位置
File dataFilterDir = new File("activemq/amq-in-action/kahadb");
KahaDBStore kaha = new KahaDBStore();
kaha.setDirectory(dataFilterDir);
// use a bigger journal file
kaha.setJournalMaxFileLength(1024*100);
// small batch means more frequent and smaller writes
kaha.setIndexWriteBatchSize(100);
// do the index write in a separate thread
kaha.setEnableIndexWriteAsync(true);
broker.setPersistenceAdapter(kaha);
// create a transport connector
broker.addConnector("tcp://localhost:61616");
broker.setUseJmx(true);
// 以下是ManagementContext的配置,从这个容器中可以取得消息队列中未执行的消息数、消费者数、出队数等等
// 设置ManagementContext
ManagementContext context = broker.getManagementContext();
context.setConnectorPort(connectorPort);
context.setJmxDomainName(jmxDomain);
context.setConnectorPath(connectorPath);
broker.start();
}
}
测试队列queue中各个状态数:
package com.activemq.queue;
import javax.management.MBeanServerConnection;
public class StateTest {
/**
* 获取状态
* @throws Exception
*/
public static void main(String[] args) throws Exception {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:"+
RunServer.connectorPort+RunServer.connectorPath);
JMXConnector connector = JMXConnectorFactory.connect(url, null);
connector.connect();
MBeanServerConnection connection = connector.getMBeanServerConnection();
// 需要注意的是,这里的jms-broker必须和上面配置的名称相同
ObjectName name = new ObjectName(RunServer.jmxDomain+":BrokerName=localhost,Type=Broker");
BrokerViewMBean mBean = (BrokerViewMBean)MBeanServerInvocationHandler.newProxyInstance(connection,
name, BrokerViewMBean.class, true);
// System.out.println(mBean.getBrokerName());
for(ObjectName queueName : mBean.getQueues()) {
QueueViewMBean queueMBean = (QueueViewMBean)MBeanServerInvocationHandler
.newProxyInstance(connection, queueName, QueueViewMBean.class, true);
System.out.println("\n------------------------------\n");
// 消息队列名称
System.out.println("States for queue --- " + queueMBean.getName());
// 队列中剩余的消息数
System.out.println("Size --- " + queueMBean.getQueueSize());
// 消费者数
System.out.println("Number of consumers --- " + queueMBean.getConsumerCount());
// 出队数
System.out.println("Number of dequeue ---" + queueMBean.getDequeueCount() );
}
}
}