该实例演示了ActiveMQ发送和异步接受文本类型消息的简单功能。
要求:熟悉Java,了解JMS,了解ActiveMQ
环境:ActiveMQ5.1.0,JDK1.5或以上,Eclipse3.2或以上。
ActiveMQ5.1.0的下载地址:http://activemq.apache.org/activemq-510-release.html ,下载apache-activemq-5.1.0-bin.zip 版本,解压即可。ActiveMQ也提供了从命令行启动的功能,需要在环境变量中配置PATH。
主要源码说明:
类com.honno.activemq.MQBroker负责启动ActiveMQ的消息代理。
代码片段:
BrokerService broker = new BrokerService();
try {
broker.addConnector("tcp://localhost:61616");
broker.start();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
类com.honno.activemq.producer.Producer生产10个文本消息,并发送出去。
代码片段:
try {
// TODO Auto-generated method stub
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnectionFactory.DEFAULT_USER,
ActiveMQConnectionFactory.DEFAULT_PASSWORD,
ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
try {
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("TEST");
MessageProducer producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
PrintlnUtil.println("Sending Messags");
for (int i = 0; i < 10; i++) {
message.setText("This is message " + (i + 1));
producer.send(message);
}
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
类com.honno.activemq.consumer.Consumer异步接收的方式消费消息。
代码片段:
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnectionFactory.DEFAULT_USER,
ActiveMQConnectionFactory.DEFAULT_PASSWORD,
ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
try {
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("TEST");
MessageConsumer consumer = session.createConsumer(destination);
PrintlnUtil.println("Consumering Messages");
consumer.setMessageListener(this);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onMessage(Message m) {
// TODO Auto-generated method stub
if (m instanceof TextMessage) {
TextMessage message = (TextMessage) m;
try {
System.out.println("Message :" + message.getText());
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
以上是几个主要类的核心代码片段。