Enterprise Java

JMX and Spring – Part 2

This post continues from Part 1 of the tutorial.

Hi, in my previous article I explained how to setup a JMX server through Spring and how to protect access to it through authentication and authorisation.

In this article I will show how to implement a simple MBean which allows users to change the level of a Log4j logger at runtime without the need to restart the application.

The Spring configuration has changed only slightly from my previous article to facilitate testing; the substance remains the same though.

The Spring configuration

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?xml version="1.0" encoding="UTF-8"?>
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
 
 
    <bean id="propertyConfigurer"
       class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jemos-jmx.properties</value>
                <value>file:///${user.home}/.secure/jmxconnector-credentials.properties</value>
            </list>
        </property>
    </bean>
 
<!-- In order to automatically detect MBeans we need to recognise Spring beans -->
    <context:component-scan base-package="uk.co.jemos.experiments.jmx.mbeans" />
 
<!-- This causes MBeans annotations to be recognised and MBeans to be registered with the JMX server -->
    <context:mbean-export default-domain="jemos.mbeans"/>
 
    <bean id="jemosJmxServer" class="org.springframework.jmx.support.ConnectorServerFactoryBean"
        depends-on="rmiRegistry">
        <property name="objectName" value="connector:name=rmi" />
        <property name="serviceUrl"
            value="service:jmx:rmi://localhost/jndi/rmi://localhost:${jemos.jmx.rmi.port}/jemosJmxConnector" />
        <property name="environment">
            <!-- the following is only valid when the sun jmx implementation is used -->
            <map>
                <entry key="jmx.remote.x.password.file" value="${user.home}/.secure/jmxremote.password" />
                <entry key="jmx.remote.x.access.file" value="${user.home}/.secure/jmxremote.access" />
            </map>
        </property>
    </bean>
 
    <bean id="rmiRegistry" class="org.springframework.remoting.rmi.RmiRegistryFactoryBean">
        <property name="port" value="${jemos.jmx.rmi.port}" />
    </bean>
 
<!-- Used for testing -->
    <bean id="clientConnector" class="org.springframework.jmx.support.MBeanServerConnectionFactoryBean"
        depends-on="jemosJmxServer">
          <property name="serviceUrl" value="service:jmx:rmi://localhost/jndi/rmi://localhost:${jemos.jmx.rmi.port}/jemosJmxConnector"/>
          <property name="environment">
            <map>
                <entry key="jmx.remote.credentials">
                  <bean factory-method="commaDelimitedListToStringArray">
                    <constructor-arg value="${jmx.username},${jmx.password}" />
                  </bean>
                </entry>
          </map>
        </property>
    </bean>
 
     
</beans>

The only part of the configuration which is of interest to us is the scanning of Spring components and the declaration of the MBean exporter (which causes also MBean annotations to be recognised and Spring beans to be registered with a JMX server as MBeans)

The LoggerConfigurator MBean

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package uk.co.jemos.experiments.jmx.mbeans;
 
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedOperationParameter;
import org.springframework.jmx.export.annotation.ManagedOperationParameters;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;
 
/**
 * MBean which allows clients to change or retrieve the logging level for a
 * Log4j Logger at runtime.
 *
 * @author mtedone
 *
 */
@Component
@ManagedResource(objectName = LoggerConfigurator.MBEAN_NAME, //
description = "Allows clients to set the Log4j Logger level at runtime")
public class LoggerConfigurator {
     
    public static final String MBEAN_NAME = "jemos.mbeans:type=config,name=LoggingConfiguration";
 
    @ManagedOperation(description = "Returns the Logger LEVEL for the given logger name")
    @ManagedOperationParameters({ @ManagedOperationParameter(description = "The Logger Name", name = "loggerName"), })
    public String getLoggerLevel(String loggerName) {
 
        Logger logger = Logger.getLogger(loggerName);
        Level loggerLevel = logger.getLevel();
 
        return loggerLevel == null ? "The logger " + loggerName
                + " has not level" : loggerLevel.toString();
 
    }
 
    @ManagedOperation(description = "Set Logger Level")
    @ManagedOperationParameters({
            @ManagedOperationParameter(description = "The Logger Name", name = "loggerName"),
            @ManagedOperationParameter(description = "The Level to which the Logger must be set", name = "loggerLevel") })
    public void setLoggerLevel(String loggerName, String loggerLevel) {
 
        Logger thisLogger = Logger.getLogger(this.getClass());
        thisLogger.setLevel(Level.INFO);
 
        Logger logger = Logger.getLogger(loggerName);
 
        logger.setLevel(Level.toLevel(loggerLevel, Level.INFO));
 
        thisLogger.info("Set logger " + loggerName + " to level "
                + logger.getLevel());
 
    }
 
}

Apart from Spring JMX annotations (in bold), this is a normal Spring bean. With those annotations however we have made an MBean of it and this bean will be registered with the JMX server at startup.

The @ManagedOperation and @ManagedOperationParameters annotations determine what gets displayed on the jconsole. One could omit these annotations, but the parameter names would not become something like p1 and p2, without giving any information on the type of parameter.

Invoking the function with, say, the value foo.bar.baz, INFO would result in the following output:

1
2
3
...snip
 
2011-08-11 21:33:36 LoggerConfigurator [INFO] Set logger foo.bar.baz to level INFO

In my next and last article for this series, I will show how to setup an MBean which alerts a listener when the HEAP memory threshold has been reached, as explained in one of my previous articles

Continue to Part 3.

Reference: JMX and Spring – Part 2 from our JCG partner Marco Tedone at the Marco Tedone’s blog blog.

Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button