一.订阅/发布模式

1.生产者

/**
* 消息生产者
*
*/
public class JMSProducer { private static final String USERNAME=ActiveMQConnection.DEFAULT_USER;
private static final String PASSWORD=ActiveMQConnection.DEFAULT_PASSWORD;
private static final String BROKEURL=ActiveMQConnection.DEFAULT_BROKER_URL;
private static final int SENDNUM=10; public static void main(String[] args) { ConnectionFactory connectionFactory;
Connection connection = null;
Session session;
Destination destination;
MessageProducer messageProducer; connectionFactory=new ActiveMQConnectionFactory
(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKEURL); try {
connection=connectionFactory.createConnection();
connection.start();
session=connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
destination=session.createTopic("FirstTopic1"); //创建topic,为目的地
messageProducer=session.createProducer(destination); //创建消息生产者
sendMessage(session, messageProducer); //发送消息
session.commit(); //提交session
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(connection!=null){
try {
connection.close();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} /**
*发送消息
*/
public static void sendMessage(Session session,MessageProducer messageProducer)throws Exception{
for(int i=0;i<JMSProducer.SENDNUM;i++){
TextMessage message=session.createTextMessage("ActiveMQ 发送消息"+i);
System.out.println("发送消息:"+"ActiveMQ 发送的消息:"+i);
messageProducer.send(message);
}
}
}

2.消息消费者

/**
* 消息消费者
*
*/
public class JMSConsumer2 { private static final String USERNAME=ActiveMQConnection.DEFAULT_USER;
private static final String PASSWORD=ActiveMQConnection.DEFAULT_PASSWORD;
private static final String BROKEURL=ActiveMQConnection.DEFAULT_BROKER_URL; public static void main(String[] args) {
ConnectionFactory connectionFactory;
Connection connection = null;
Session session;
Destination destination;
MessageConsumer messageConsumer; connectionFactory=new ActiveMQConnectionFactory
(JMSConsumer2.USERNAME, JMSConsumer2.PASSWORD, JMSConsumer2.BROKEURL); try {
connection=connectionFactory.createConnection();
connection.start();
session=connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
destination=session.createTopic("FirstTopic1"); //指定消费的topic
messageConsumer=session.createConsumer(destination); //创建消息消费者
messageConsumer.setMessageListener(new Listener2()); //注册监听
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

3.监听器

/**
* 监听器
*/
public class Listener implements MessageListener{ @Override
public void onMessage(Message message) {
// TODO Auto-generated method stub
try {
System.out.println("监听器:"+((TextMessage)message).getText());
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

分别运行生产者,消费者代码,观察控制台

Apache  ActiveMQ 实践 &lt;二&gt;-LMLPHP

05-28 06:17