How to query the number of active sessions with JB

2019-06-07 17:57发布

问题:

We used to query the active session count by using the following code up to JBoss 7:

ObjectName name = new ObjectName(jboss.web:type=Manager,path=/MyWebApp,host=default-host);
MBeanServer jboss = MBeanServerLocator.locateJBoss();
this.sessions = new Long((Integer) jboss.getAttribute(name, "activeSessions"));

That no longer works with JBoss Wildfly. I can't really find the proper documentation to access the same information with the current version of JBoss AS.

I've come across some links like http://blog.akquinet.de/2014/09/15/monitoring-the-jboss-eap-wildfly-application-server-with-the-command-line-interface-cli/ which imply a totally different location of that information – but I can't figure out how to access it via Java code.

/deployment=example.ear/subdeployment=example-web.war/subsystem=under

The old reference to -Dorg.apache.tomcat.util.ENABLE_MODELER=true from JBoss 7 didn't help either. My older question via MBean "jboss.web:type=Manager,path=/,host=localhost" not found doesn't work anymore.

回答1:

Assuming you are deploying a WAR file; the ObjectName should be something similar to jboss.as:deployment=YourWAR.war,subsystem=undertow.

Note that in case of WildFly - management native port is 9990 instead of 9999.

If you are using maven, add the following dependency.

    <dependency>
        <groupId>org.jboss.remotingjmx</groupId>
        <artifactId>remoting-jmx</artifactId>
        <version>2.0.0.Final</version>
    </dependency>

Sample example:

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

    ObjectName mBeanName = new ObjectName("jboss.as:deployment=wildfly-helloworld-rs.war,subsystem=undertow");

    String host = "localhost";
    int port = 9990;  // management-native port

    String urlString = System.getProperty("jmx.service.url", "service:jmx:http-remoting-jmx://" + host + ":" + port);
    JMXServiceURL serviceURL = new JMXServiceURL(urlString);
    JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
    MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();

    System.out.println("Value via JMX: activeSessions: " + connection.getAttribute(mBeanName, "activeSessions"));
    System.out.println("Value via JMX: contextRoot: " + connection.getAttribute(mBeanName, "contextRoot"));
}

If your WAR file is bundled inside an EAR file; then the ObjectName shall be something similar to jboss.as:deployment=YourEAR.ear,subdeployment=YourWAR.war,subsystem=undertow"

For more details, see https://docs.jboss.org/author/display/WFLY8/JMX+subsystem+configuration