activemq 读取topic 所有消息
时间: 2023-09-21 20:06:37 浏览: 47
要从 ActiveMQ 中读取一个 Topic 的所有消息,可以使用 JMS(Java Message Service)来实现。以下是一个使用 Java 编写的示例代码:
```java
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
public class TopicReader {
public static void main(String[] args) {
// 设置 ActiveMQ 连接参数
String brokerUrl = "tcp://localhost:61616";
String username = "admin";
String password = "admin";
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(username, password, brokerUrl);
try {
// 创建连接
Connection connection = connectionFactory.createConnection();
connection.start();
// 创建会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 创建 Topic
Topic topic = session.createTopic("your_topic_name");
// 创建消费者
MessageConsumer consumer = session.createConsumer(topic);
// 消费消息
Message message;
while ((message = consumer.receive()) != null) {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
String text = textMessage.getText();
System.out.println("Received message: " + text);
}
}
// 关闭连接
consumer.close();
session.close();
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
```
请确保在运行代码之前已经启动了 ActiveMQ 服务器,并且替换 `brokerUrl` 和 `your_topic_name` 为正确的 ActiveMQ 连接URL和你要读取消息的 Topic 名称。