ActiveMQ两种消息模式

一、点对点模式(p2p)



二、发布/订阅模式(pub/sub)



示例:

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



猜你喜欢

转载自javafu.iteye.com/blog/2377109