插件窝 干货文章 Tomcat添加JMS远程监控的代码示例

Tomcat添加JMS远程监控的代码示例

ConnectionFactor Connection JMS Session 564    来源:    2025-04-01

Tomcat 添加 JMS 远程监控的代码示例

要在 Tomcat 中添加 JMS 远程监控功能,您需要配置 JMS 连接工厂、目的地,并设置适当的监听器。以下是完整的实现步骤和代码示例:

1. 配置 context.xml

首先,在 Tomcat 的 context.xml 文件中添加 JMS 资源:

<Context>
    <!-- JMS 连接工厂 -->
    <Resource name="jms/ConnectionFactory" 
              auth="Container"
              type="org.apache.activemq.ActiveMQConnectionFactory"
              factory="org.apache.activemq.jndi.JNDIReferenceFactory"
              brokerURL="tcp://your.activemq.host:61616"
              brokerName="LocalActiveMQBroker"/>

    <!-- 监控队列 -->
    <Resource name="jms/monitoringQueue" 
              auth="Container"
              type="org.apache.activemq.command.ActiveMQQueue"
              factory="org.apache.activemq.jndi.JNDIReferenceFactory"
              physicalName="monitoring.queue"/>
</Context>

2. 配置 web.xml

在您的 web 应用的 web.xml 中添加资源引用:

<resource-ref>
    <description>JMS Connection Factory</description>
    <res-ref-name>jms/ConnectionFactory</res-ref-name>
    <res-type>javax.jms.ConnectionFactory</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

<resource-ref>
    <description>Monitoring Queue</description>
    <res-ref-name>jms/monitoringQueue</res-ref-name>
    <res-type>javax.jms.Queue</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

3. 创建 JMS 监控监听器

创建一个 Servlet 上下文监听器来初始化 JMS 连接和监听器:

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

public class JmsMonitoringInitializer implements ServletContextListener {

    private Connection connection;
    private Session session;
    private MessageConsumer consumer;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            // 获取 JNDI 上下文
            Context ctx = new InitialContext();

            // 查找连接工厂和队列
            ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("java:comp/env/jms/ConnectionFactory");
            Queue monitoringQueue = (Queue) ctx.lookup("java:comp/env/jms/monitoringQueue");

            // 创建连接和会话
            connection = connectionFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // 创建消费者并设置消息监听器
            consumer = session.createConsumer(monitoringQueue);
            consumer.setMessageListener(new MonitoringMessageListener());

            // 启动连接
            connection.start();

            System.out.println("JMS Monitoring Listener initialized successfully");

        } catch (Exception e) {
            throw new RuntimeException("Failed to initialize JMS monitoring", e);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        try {
            if (consumer != null) consumer.close();
            if (session != null) session.close();
            if (connection != null) connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    private static class MonitoringMessageListener implements MessageListener {
        @Override
        public void onMessage(Message message) {
            try {
                if (message instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message;
                    System.out.println("Received monitoring message: " + textMessage.getText());

                    // 在这里处理监控消息
                    // 可以解析消息内容并采取相应操作
                }
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}

4. 注册监听器

web.xml 中注册这个监听器:

<listener>
    <listener-class>com.yourpackage.JmsMonitoringInitializer</listener-class>
</listener>

5. 发送监控消息的示例

以下是如何从应用程序发送监控消息的示例:

import javax.jms.*;
import javax.naming.*;

public class MonitoringMessageSender {

    public void sendMonitoringMessage(String messageText) {
        Connection connection = null;
        Session session = null;
        MessageProducer producer = null;

        try {
            Context ctx = new InitialContext();
            ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("java:comp/env/jms/ConnectionFactory");
            Queue monitoringQueue = (Queue) ctx.lookup("java:comp/env/jms/monitoringQueue");

            connection = connectionFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            producer = session.createProducer(monitoringQueue);

            TextMessage message = session.createTextMessage(messageText);
            producer.send(message);

            System.out.println("Sent monitoring message: " + messageText);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (producer != null) producer.close();
                if (session != null) session.close();
                if (connection != null) connection.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}

6. 监控消息格式建议

为了有效监控,建议使用结构化的消息格式,如 JSON:

// 创建监控消息
JSONObject monitoringData = new JSONObject();
monitoringData.put("timestamp", System.currentTimeMillis());
monitoringData.put("server", "Tomcat-1");
monitoringData.put("metric", "memory_usage");
monitoringData.put("value", "75%");

// 发送消息
new MonitoringMessageSender().sendMonitoringMessage(monitoringData.toString());

注意事项

  1. 确保 Tomcat 服务器可以访问 ActiveMQ 服务器(或您使用的其他 JMS 提供者)
  2. 在生产环境中,添加适当的错误处理和重试机制
  3. 考虑消息大小和频率,避免对系统性能造成影响
  4. 对于安全性要求高的环境,配置 JMS 连接的用户名/密码和 SSL
  5. 考虑使用连接池提高性能

依赖项

确保您的项目中包含以下依赖(Maven 示例):

<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-client</artifactId>
    <version>5.15.12</version>
</dependency>
<dependency>
    <groupId>javax.jms</groupId>
    <artifactId>javax.jms-api</artifactId>
    <version>2.0.1</version>
</dependency>

以上代码示例提供了在 Tomcat 中实现 JMS 远程监控的基本框架,您可以根据具体需求进行调整和扩展。