Aide mémoire : JMX de base

Aide mémoire (Développement) / Uncategorized
Petit aide mémoire pour utiliser un MBean avec une connexion JMX

1. Interface MBean
2. L’implémentation MBean
3. Lanceurs
4. Sources

1. Interface MBean

public interface BaseMBean {

    String OBJECT_NAME = "com.opera.my.jmx:type=BaseMBean";

    int getValeur();

    void setValeur(int valeur);
}

2. L’implémentation MBean

public class Base implements BaseMBean {

    int valeur = 0;

    @Override
    public int getValeur() {
        return valeur;
    }

    @Override
    public synchronized void setValeur(int val) {
        this.valeur = val;
    }
}

3. Lanceurs
Serveur :

    public static void main(String[] args) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            ObjectName name = new ObjectName(BaseMBean.OBJECT_NAME);
            BaseMBean mbean = new Base();
            // enregistrement 		
            mbs.registerMBean(mbean, name);
            System.out.println("Lancement ...");
            while (true) {
                Thread.sleep(1000);
                mbean.setValeur(mbean.getValeur() + 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

/!\ il faut ajouter les options suivantes à la VM :

-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=12345 
-Dcom.sun.management.jmxremote.authenticate=false 
-Dcom.sun.management.jmxremote.ssl=false

Client :

    public static final String HOST = "127.0.0.1";
    public static final String PORT = "12345";

    public static void main(String[] args) throws IOException, MalformedObjectNameException {
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + HOST + ":" + PORT + "/jmxrmi");
        JMXConnector jmxConnector = JMXConnectorFactory.connect(url);
        MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
        ObjectName mbeanName = new ObjectName(BaseMBean.OBJECT_NAME);
        //Get MBean proxy instance that will be used to make calls to registered MBean 	
        BaseMBean mbeanProxy = (BaseMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServerConnection, mbeanName, BaseMBean.class, true);
        //let's make some calls to mbean through proxy and see the results. 	
        System.out.println("ancienne valeur :" + mbeanProxy.getValeur());
        mbeanProxy.setValeur(5);
        System.out.println("nouvelle valeur :" + mbeanProxy.getValeur());
        //close the connection 	
        jmxConnector.close();
    }

4. Sources
http://www.jmdoudoux.fr/java/dej/chap-jmx.htm
http://www.journaldev.com/1359/java-jmx-client-example-and-jmx-authentication-with-config-files-for-role-based-access