ActiveMQ 发布订阅者模式

本文详细介绍了如何使用ActiveMQ实现消息的发送与接收。首先,创建ActiveMQ连接工厂并建立连接,然后创建Session,通过Session获取Topic并创建消息发送者。接着,发送文本消息到Topic。在消费者端,同样建立连接和Session,创建Topic和消息监听器,当接收到消息时手动签收。该示例展示了基于TCP的点对点消息传递流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 消息的发送方编写—生产者

创建连接工厂对象

ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(tcp://localhost:61616);

从工厂获取连接

Connection connection = connectionFactory.createConnection()

连接MQ服务
connection.start();
获取session连接对象
//是否开启事务,签收模式,这里是不开启事务和自动应答

Session session = connection.createSession(Boolean.FALSE, Session.CLIENT_ACKNOWLEDGE);

通过Session获取Topic

Topic topic = session.createTopic("zzfTopic")

通过session创建消息的发送者

MessageProducer messageProducer = session.createProducer(topic );

通过session创建消息对象

TextMessage textMessage = session.createTextMessage("ping")

发送消息

messageProducer .send(textMessage );

关闭资源

messageProducer .close();
session.close();
commection.close();
  1. 消息的接收方编写—消费者

创建连接工厂对象

ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(tcp://localhost:61616);

从工厂获取连接

Connection connection = connectionFactory.createConnection()

连接MQ服务
connection.start();
获取session连接对象
//是否开启事务,签收模式,这里是不开启事务和自动应答

Session session = connection.createSession(Boolean.FALSE, Session.CLIENT_ACKNOWLEDGE);

通过Session获取Topic

Topic topic = session.createTopic("zzfTopic")

通过session创建消息的发送者

MessageConsumer consumer = session.createConsumer(topic );

指定消息监听器

consumer.setMessageListener(new MessageListener){
	public void onMessage(Message message){
		TextMessage textMessage = (TextMessage)  message;
		System.out.println(textMessage.getText)
		//手工去签收消息,另起一个线程(TCP)去通知我们的MQ服务,确认签收。
					textMessage.acknowledge();
	}

连接资源不用关闭,接受者需要持续运行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值