ActiveMQ两种消息模式

[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]

示例:


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();
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值