My linux world » Java Spring – Jmx

Java Spring - Jmx


Contents

Prerequistes

Please read : Java spring – quickstart

Configuration

JmxConfig.java

@Configuration
@EnableMBeanExport
public class JmxConfig {
 
    @Bean
    public DiscountService discountService() {
        return new DiscountService();
    }
 
    @Bean
    public MBeanServerFactoryBean mbeanServer() {
        return new MBeanServerFactoryBean();
    }
 
    @Bean
    public RmiRegistryFactoryBean registry() {
        return new RmiRegistryFactoryBean();
    }
 
    @Bean
    @DependsOn("registry")
    public ConnectorServerFactoryBean connectorServer() throws MalformedObjectNameException {
        ConnectorServerFactoryBean connectorServerFactoryBean = new ConnectorServerFactoryBean();
        connectorServerFactoryBean.setObjectName("connector:name=rmi");
        connectorServerFactoryBean.setServiceUrl("service:jmx:rmi://localhost/jndi/rmi://localhost:1099/connector");
        return connectorServerFactoryBean;
    }
 
}

DiscountService

@ManagedResource
public class DiscountService {
 
    private AtomicInteger globalDiscount = new AtomicInteger(12);
 
    /**
     * @return
     */
    public int calculateDiscount() {
        return globalDiscount.get() * 2;
    }
 
    /**
     * @return
     */
    @ManagedOperation
    public int checkGlobalDiscount() {
        return globalDiscount.get();
    }
 
    /**
     * @param newDiscount
     */
    @ManagedOperation
    public void modifyGlobalDiscount(int newDiscount) {
        globalDiscount.set(newDiscount);
    }
}

Request

JConsole

You can request the jmx server using jconsole :

Using API

private static final String CHECK_GLOBAL_DISCOUNT_METHOD_NAME = "checkGlobalDiscount";
private static final String MODIFY_GLOBAL_DISCOUNT_METHOD_NAME = "modifyGlobalDiscount";
 
// given
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost/jndi/rmi://localhost:1099/connector");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
 
MBeanServerConnection connection  = jmxc.getMBeanServerConnection();
ObjectName objectName = new ObjectName("net.rabahi.spring.jmx:name=discountService,type=DiscountService");
 
// when
Integer oldDiscount = (Integer) connection.invoke(objectName, CHECK_GLOBAL_DISCOUNT_METHOD_NAME, null, null);
Integer newDiscount = ++oldDiscount;
connection.invoke(objectName, MODIFY_GLOBAL_DISCOUNT_METHOD_NAME, new Object[]{newDiscount}, new String[]{int.class.getName()});
Integer currentDiscount = (Integer) connection.invoke(objectName, CHECK_GLOBAL_DISCOUNT_METHOD_NAME, null, null);

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.