java生产消费activemq

小小编辑 1年前 ⋅ 123 阅读

在Java中,可以使用 ActiveMQ 的 JMS(Java Message Service)API 来实现生产者和消费者,将数据发送到 ActiveMQ 和从 ActiveMQ 接收数据。以下是一个简单的示例代码,演示如何在Java中实现 ActiveMQ 生产者和消费者: ActiveMQ 生产者: import org.apache.activemq.ActiveMQConnectionFactory; import javax.jms.*;

public class ActiveMQProducerExample { public static void main(String[] args) { String brokerURL = "tcp://localhost:61616"; String queueName = "test-queue";

    try {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerURL);
        Connection connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(queueName);
        MessageProducer producer = session.createProducer(destination);

        for (int i = 0; i < 10; i++) {
            String message = "Message " + i;
            TextMessage textMessage = session.createTextMessage(message);
            producer.send(textMessage);
            System.out.println("Sent: " + message);
            Thread.sleep(1000);
        }

        session.close();
        connection.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

ActiveMQ 消费者:

import org.apache.activemq.ActiveMQConnectionFactory; import javax.jms.*;

public class ActiveMQConsumerExample { public static void main(String[] args) { String brokerURL = "tcp://localhost:61616"; String queueName = "test-queue";

    try {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerURL);
        Connection connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(queueName);
        MessageConsumer consumer = session.createConsumer(destination);

        while (true) {
            Message message = consumer.receive();
            if (message instanceof TextMessage) {
                String text = ((TextMessage) message).getText();
                System.out.println("Received: " + text);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

} Maven POM文件:

<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-all</artifactId>
    <version>5.16.3</version>
</dependency>

在上面的示例中,我们使用 ActiveMQConnectionFactory 创建了一个 ActiveMQ 连接,并使用 Session 和 MessageProducer 实现了一个简单的 ActiveMQ 生产者,使用 Session 和 MessageConsumer 实现了一个简单的 ActiveMQ 消费者。请注意,具体的 ActiveMQ 代理连接 URL 和队列名称需要根据你的 ActiveMQ 配置进行调整。