java连接ActiveMQ实现收发消息

ActionMQ 安装好后

java实现连接 ActiveMQ 直接上代码

程序一:消息生产者  ActiveMQProducer

image

 pom.xml

    <!-- ActiveMQ -->
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-all</artifactId>
      <version>5.16.5</version>
    </dependency>
    <!-- ActiveMQ 自带的连接池 -->
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-jms-pool</artifactId>
      <version>5.16.5</version>
    </dependency>

JmsPoolUtil.java

package com.ActiveMQ.ActiveMQ;

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

public class JmsPoolUtil {
    private static final String BROKER_URL = "tcp://192.168.1.145:61616";
    private static final PooledConnectionFactory pooledConnectionFactory;

    static {
        // 1. 创建 ActiveMQ 原生连接工厂
        ActiveMQConnectionFactory activeMQFactory = new ActiveMQConnectionFactory(BROKER_URL);

        // 2. 配置连接池
        pooledConnectionFactory = new PooledConnectionFactory();
        pooledConnectionFactory.setConnectionFactory(activeMQFactory);
        pooledConnectionFactory.setMaxConnections(10);          // 最大连接数
        pooledConnectionFactory.setMaximumActiveSessionPerConnection(50); // 每个连接最大会话数
        pooledConnectionFactory.setIdleTimeout(30000);       // 空闲超时(毫秒)
        pooledConnectionFactory.setBlockIfSessionPoolIsFull(true); // 会话池满时阻塞
    }

    public static Connection getConnection() throws JMSException {
        return pooledConnectionFactory.createConnection();
    }

    public static void shutdown() {
        pooledConnectionFactory.stop();
    }
}

PooledProducer.java

package com.ActiveMQ.ActiveMQ;

import javax.jms.*;

public class PooledProducer {
    
    private static final String QUEUE_NAME = "queue.joincallcc";

    public void sendMessage(String text) throws JMSException {
        Connection connection = null;
        Session session = null;
        MessageProducer producer = null;

        try {
            // 从池中获取连接
            connection = JmsPoolUtil.getConnection();
            connection.start();

            // 创建会话和生产者
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue(QUEUE_NAME);
            producer = session.createProducer(destination);

            // 发送消息
            TextMessage message = session.createTextMessage(text);
            producer.send(message);
            System.out.println("[ActiveMQ]发送: " + text);

        } finally {
            // 关闭资源(连接由池管理,无需关闭)
            if (producer != null) producer.close();
            if (session != null) session.close();
        }
    }
}

App.java

package com.ActiveMQ;

import com.ActiveMQ.ActiveMQ.JmsPoolUtil;
import com.ActiveMQ.ActiveMQ.PooledProducer;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) {
        System.out.println("Hello World!");

        PooledProducer producer = new PooledProducer();
        try {
            producer.sendMessage("Hello from Pooled Producer! 我发送的第一条ActiveMQ消息");
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            JmsPoolUtil.shutdown(); // 程序退出时关闭连接池
        }
        /*
        //最简单直接的连接ActiveMQ的写法,仅用于连接测试
        try {
            ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://192.168.1.145:61616");
            Connection connection = factory.createConnection();
            connection.start();
            System.out.println("连接成功!");
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }*/
    }
}

 程序二:消息消费者  ActiveMQConsumer

image

 pom.xml

    <!-- ActiveMQ -->
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-client</artifactId> <!-- 核心客户端 -->
      <version>5.16.5</version>
    </dependency>
    <!-- ActiveMQ 自带的连接池 -->
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-jms-pool</artifactId>
      <version>5.16.5</version>
    </dependency>
  </dependencies>

JmsPoolUtil.java

package com.ActiveMQConsumer.ActiveMQ;

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

public class JmsPoolUtil {
    private static final String BROKER_URL = "tcp://192.168.1.145:61616";
    private static final PooledConnectionFactory pooledConnectionFactory;

    static {
        // 1. 创建 ActiveMQ 原生连接工厂
        ActiveMQConnectionFactory activeMQFactory = new ActiveMQConnectionFactory(BROKER_URL);

        // 2. 配置连接池
        pooledConnectionFactory = new PooledConnectionFactory();
        pooledConnectionFactory.setConnectionFactory(activeMQFactory);
        pooledConnectionFactory.setMaxConnections(10);          // 最大连接数
        pooledConnectionFactory.setMaximumActiveSessionPerConnection(50); // 每个连接最大会话数
        pooledConnectionFactory.setIdleTimeout(30_000);       // 空闲超时(毫秒)
        pooledConnectionFactory.setBlockIfSessionPoolIsFull(true); // 会话池满时阻塞
    }

    public static Connection getConnection() throws JMSException {
        return pooledConnectionFactory.createConnection();
    }

    public static void shutdown() {
        pooledConnectionFactory.stop();
    }
}

PooledConsumer.java

package com.ActiveMQConsumer.ActiveMQ;

import com.ActiveMQConsumer.App;

import javax.jms.*;
import java.util.concurrent.CountDownLatch;

public class PooledConsumer {
    private static final String QUEUE_NAME = "queue.joincallcc";  //队列名
    private volatile boolean running = true;
    private final App appInstance; // 添加 App 实例引用

    private final CountDownLatch keepAliveLatch = new CountDownLatch(1);

    private Connection connection;

    // 构造函数注入 App 实例
    public PooledConsumer(App app) {
        this.appInstance = app;
    }

    //方案一 CountDownLatch 实现持续监听方式
    public void startListening() throws JMSException {
        try {
            // 1. 获取连接并启动
            connection = JmsPoolUtil.getConnection();
            connection.start();

            // 2. 创建会话和消费者
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME));

            // 3. 设置消息监听器
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    try {
                        if (message instanceof TextMessage) {
                            String msgText = ((TextMessage) message).getText();
                            System.out.println("[RECEIVED] " + msgText);
                            // 调用App的消息处理方法
                            appInstance.recMsgEvent(msgText);
                        }
                    } catch (JMSException e) {
                        System.err.println("消息处理异常: " + e.getMessage());
                    }
                }
            });

            System.out.println("✅ 消费者已启动,正在监听队列: " + QUEUE_NAME);
            keepAliveLatch.await(); // 4. 保持阻塞直到调用stop()

        } catch (InterruptedException e) {
            System.out.println("消费者被中断");
            Thread.currentThread().interrupt();
        } finally {
            closeResources();
        }
    }

    public void stop() {
        System.out.println("🛑 停止消费者...");
        keepAliveLatch.countDown(); // 释放阻塞
    }

    private void closeResources() {
        try {
            if (connection != null) {
                connection.close();
            }
            System.out.println("资源已释放");
        } catch (JMSException e) {
            System.err.println("关闭连接异常: " + e.getMessage());
        }
    }

    /*
    //方案二 Thread.sleep 休眠方式
    public void startListening() throws JMSException {
        Connection connection = null;
        Session session = null;
        MessageConsumer consumer = null;

        try {
            connection = JmsPoolUtil.getConnection();
            connection.start();

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

            // 设置消息监听器
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    try {
                        if (message instanceof TextMessage) {
                            TextMessage textMessage = (TextMessage) message;
                            String msgContent = textMessage.getText();
                            System.out.println("[ActiveMQ]收到消息: " + msgContent);

                            // 调用 App 类的 recMsgEvent 方法
                            appInstance.recMsgEvent(msgContent);
                        }
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });

            // 保持监听状态
            System.out.println("ActiveMQ消费者已启动,开始监听队列: " + QUEUE_NAME);
            while (running) {
                Thread.sleep(1000); // 防止CPU空转
            }

        } catch (InterruptedException e) {
            System.out.println("ActiveMQ消费者被中断");
        } finally {
            // 清理资源
            if (consumer != null) consumer.close();
            if (session != null) session.close();
            if (connection != null) connection.close();
            System.out.println("ActiveMQ消费者已停止");
        }
    }

    public void stop() {
        running = false;
    }
    */
}

App.java

package com.ActiveMQConsumer;

import com.ActiveMQConsumer.ActiveMQ.JmsPoolUtil;
import com.ActiveMQConsumer.ActiveMQ.PooledConsumer;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) {
        System.out.println("Hello World!");

        App app = new App();
        try {
            // 必须将 consumer 声明为 final
            final PooledConsumer consumer = new PooledConsumer(app);

            // 添加关闭钩子(优雅停机)
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("JVM 关闭中,执行清理...");
                    long startTime = System.currentTimeMillis();

                    try {
                        // 第一步:停止接收新消息
                        consumer.stop(); // 现在可以访问 final 的 consumer
                        System.out.println("消费者已优雅停止");
                        // 第二步:等待处理中的消息完成(可选)
                        Thread.sleep(500);
                        // 第三步:关闭连接池
                        JmsPoolUtil.shutdown();
                    } catch (Exception e) {
                        System.err.println("停止消费者时出错: " + e.getMessage());
                    } finally {

                        System.out.println("清理完成,耗时 " +
                                (System.currentTimeMillis() - startTime) + "ms");
                    }
                }
            }));

            consumer.startListening();

        } catch (Exception e) {
            System.err.println("消费者启动失败: " + e.getMessage());
            System.exit(1);
        } finally {
            JmsPoolUtil.shutdown();
        }
    }


    public void recMsgEvent(String message) {
        // 在这里处理收到的消息
        System.out.println("处理消息: " + message);
        // 添加您的业务逻辑...
    }



}

 

posted @ 2025-08-05 14:14  海乐学习  阅读(22)  评论(0)    收藏  举报