您现在的位置是:首页 >科技 > 2025-03-14 14:46:48 来源:

📚 ActiveMQ学习教程 🌟 2. 简单示例

导读 大家好!今天我们继续来探索 Apache ActiveMQ 的世界!如果还不了解 ActiveMQ 是什么,可以回顾上一篇文章哦~ 📖✨这次我们将通过一...

大家好!今天我们继续来探索 Apache ActiveMQ 的世界!如果还不了解 ActiveMQ 是什么,可以回顾上一篇文章哦~ 📖✨

这次我们将通过一个简单的例子,快速入门 ActiveMQ 的使用。首先,确保已经安装好了 ActiveMQ 服务并成功启动!🎉

🏁 示例:发送一条消息

假设我们有两个程序,一个是生产者(Producer),另一个是消费者(Consumer)。生产者负责发送消息到队列中,而消费者则从队列中接收消息。

🛠️ 生产者代码片段

```java

import org.apache.activemq.ActiveMQConnectionFactory;

public class Producer {

public static void main(String[] args) throws Exception {

// 创建连接工厂

ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");

// 建立连接

var connection = factory.createConnection();

connection.start();

// 创建会话

var session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

var destination = session.createQueue("TEST.QUEUE");

// 发送消息

var producer = session.createProducer(destination);

producer.send(session.createTextMessage("Hello ActiveMQ!"));

System.out.println("消息已发送!");

}

}

```

📥 消费者代码片段

```java

import org.apache.activemq.ActiveMQConnectionFactory;

public class Consumer {

public static void main(String[] args) throws Exception {

ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");

var connection = factory.createConnection();

connection.start();

var session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

var destination = session.createQueue("TEST.QUEUE");

var consumer = session.createConsumer(destination);

var message = consumer.receive();

if (message instanceof TextMessage) {

System.out.println("接收到消息:" + ((TextMessage) message).getText());

}

}

}

```

运行这两个程序后,你会看到生产者成功发送了一条消息,消费者也顺利接收到它!💡

通过这个简单的例子,我们可以感受到 ActiveMQ 的强大与便捷!如果你有更多问题或需要更复杂的功能,欢迎继续关注后续内容!💬

🌟 小提示:记得检查 ActiveMQ 是否正常运行,以及网络配置是否正确哦!

ActiveMQ Java 消息队列