1.首先启动activeMQ的服务
ActiveMQ技术学习 https://www.itkc8.com
public class RunServer {
/** 启动activeMQ服务 */
public static void main(String[] args) throws Exception {
RunServer rs = new RunServer();
BrokerService broker = rs.startServer();
}
public BrokerService startServer() throws Exception{
// java代码调用activemq相关的类来构造并启动brokerService
BrokerService broker = new BrokerService();
// 以下是持久化的配置
// 持久化文件存储位置
File dataFilterDir = new File("targer/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);
//broker.setDataDirectory("data/");
// 以下是ManagementContext的配置,从这个容器中可以取得消息队列中未执行的消息数、消费者数、出队数等等
// 设置ManagementContext
ManagementContext context = broker.getManagementContext();
context.setConnectorPort(2011);
context.setJmxDomainName("my-broker");
context.setConnectorPath("/jmxrmi");
broker.start();
System.in.read();
return broker;
}
2.发送消息
public class Sender {
private static final int SEND_NUMBER = 1;
public static void main(String[] args) {
// ConnectionFactory :连接工厂,JMS 用它创建连接
ConnectionFactory connectionFactory;
// Connection :JMS 客户端到JMS Provider 的连接
Connection connection = null;
// Session: 一个发送或接收消息的线程
Session session;
// Destination :消息的目的地;消息发送给谁.
Destination destination;
// MessageProducer:消息发送者
MessageProducer producer;
// TextMessage message;
// 构造ConnectionFactory实例对象,此处采用ActiveMq的实现jar
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);
// 获取session注意参数值xingbo.xu-queue是一个服务器的queue,须在在ActiveMq的console配置
destination = session.createQueue("test-persistence");
// 得到消息生成者【发送者】
producer = session.createProducer(destination);
// 设置不持久化,可以更改
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
// 构造消息
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);
}
}
3.收消息
public class Receiver {
public static void main(String[] args) {
// ConnectionFactory :连接工厂,JMS 用它创建连接
ConnectionFactory connectionFactory;
// Connection :JMS 客户端到JMS Provider 的连接
Connection connection = null;
// Session: 一个发送或接收消息的线程
Session session;
// Destination :消息的目的地;消息发送给谁.
Destination destination;
// 消费者,消息接收者
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);
//test-queue跟sender的保持一致,一个创建一个来接收
destination = session.createQueue("test-persistence");
consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message arg0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("==================");
try {
System.out.println("RECEIVE1第一个获得者:"
+ ((TextMessage) arg0).getText());
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (null != connection)
connection.close();
} catch (Throwable ignore) {
}
}
}
}
4.获取消息的状态,也就是上面所说的获得消息队列中未执行的消息数、消费者数、出队数等等
public class StateTest {
/**
* 获取状态
* @throws Exception
*/
public static void main(String[] args) throws Exception {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:2011/jmxrmi");
JMXConnector connector = JMXConnectorFactory.connect(url, null);
connector.connect();
MBeanServerConnection connection = connector.getMBeanServerConnection();
// 需要注意的是,这里的my-broker必须和上面配置的名称相同
ObjectName name = new ObjectName("my-broker: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() );
}
}
}
ActiveMQ技术学习 https://www.itkc8.com