[size=large]一、点对点模式(p2p)[/size]
[img]http://dl2.iteye.com/upload/attachment/0125/2000/88baa79f-66aa-3f5d-9094-8780377e5ca0.png[/img]
[size=large]二、发布/订阅模式(pub/sub)[/size]
[img]http://dl2.iteye.com/upload/attachment/0125/2002/9723a6ae-d8b3-33f3-8e7a-a64a98c32224.png[/img]
示例:
[img]http://dl2.iteye.com/upload/attachment/0125/2000/88baa79f-66aa-3f5d-9094-8780377e5ca0.png[/img]
[size=large]二、发布/订阅模式(pub/sub)[/size]
[img]http://dl2.iteye.com/upload/attachment/0125/2002/9723a6ae-d8b3-33f3-8e7a-a64a98c32224.png[/img]
示例:
public class Producer {
// 建立connectionFactory工厂对象
private ActiveMQConnectionFactory connectionFactory;
// 连接对象
private Connection connection;
// session对象
private Session session;
// 生产者
private MessageProducer producer;
public Producer() {
this.connectionFactory = new ActiveMQConnectionFactory();
try {
this.connection = connectionFactory.createConnection("fu", "fu");
this.connection.start();
//参一:未开启事务,参二,自动签收
this.session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
this.producer = session.createProducer(null);
} catch (Exception e) {
e.printStackTrace();
}
}
public void send() throws Exception {
//创建publish/subscribe消息模式
Destination destination = this.session.createTopic("topic1");
Message m = this.session.createTextMessage("一条消息");
this.producer.send(destination, m);
//关闭连接
this.connection.close();
}
public static void main(String[] args) throws Exception {
Producer p = new Producer();
p.send();
}
}
public class Comsumer {
// 建立connectionFactory工厂对象
private ActiveMQConnectionFactory connectionFactory;
// 连接对象
private Connection connection;
// session对象
private Session session;
// 生产者
private MessageConsumer consumer;
// 目标地址
private Destination destination;
public Comsumer() {
this.connectionFactory = new ActiveMQConnectionFactory();
try {
this.connection = connectionFactory.createConnection("fu", "fu");
this.connection.start();
//参一:未开启事务,参二,自动签收
this.session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
//创建publish/subscribe消息模式
this.destination = this.session.createTopic("topic1");
// 消息过滤的不是消息本身,而是过滤消息附带的某些属性
this.consumer = session.createConsumer(destination);
} catch (Exception e) {
e.printStackTrace();
}
}
public void recever() throws Exception {
// 消息异步接收:当消息到达时,ActiveMQ主动通知消费端,可以注册一个MessageListener类实现onMessage方法,监听MQ送达消息
this.consumer.setMessageListener(new Listener());
}
class Listener implements MessageListener {
public void onMessage(Message message) {
try {
TextMessage m = (TextMessage) message;
System.out.println(m.getText()+"===============");
} catch (JMSException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
Comsumer c = new Comsumer();
c.recever();
}
}