【Java】JMX (Java Management Extensions) / MBean (Management Bean)

用語整理

JMX

 * Java Management Extensions
 * 外部からJava アプリケーションをモニタおよび管理するための仕組み

MBean

 * Management Bean
 * JMXでアクセスする管理用オブジェクト

MBeanServer

 * 外部との通信を行うコンポーネント

主なクラス・メソッド

 * MBeanServer
    + queryNames()
    + getMBeanInfo
    + getAttribute()
    + invoke()
 * MBeanServerFactory
    + findMBeanServer()

サンプル

 * 以下を参考に作ってみた
http://alvinalexander.com/blog/post/java/source-code-java-jmx-hello-world-application

Main.java

package com.sample.mbeans;

import java.lang.management.ManagementFactory;

import javax.management.MBeanServer;
import javax.management.ObjectName;

public class Main {
   private MBeanServer mbs = null;

   public Main() {

      // Get the platform MBeanServer
      mbs = ManagementFactory.getPlatformMBeanServer();

      // Unique identification of MBeans
      Hello helloBean = new Hello();
      ObjectName helloName = null;

      try {
         // Uniquely identify the MBeans and register them with the platform MBeanServer 
         helloName = new ObjectName("FOO:name=IHelloBean");
         mbs.registerMBean(helloBean, helloName);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   // Utility method: so that the application continues to run
   private void waitForEnterPressed() {
      try {
         System.out.println("Press  to continue...");
         System.in.read();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void main(String argv[]) {
      Main agent = new Main();
      System.out.println("SimpleAgent is running...");
      agent.waitForEnterPressed();
   }
}

HelloMBean.java

package com.sample.mbeans;

public interface HelloMBean {
   public void setMessage(String message);

   public String getMessage();

   public void sayHello();
}

Hello.java

package com.sample.mbeans;

public class Hello implements HelloMBean {
   private String message = null;
   
   public Hello() {
      message = "Hello, world";
   }
 
   public Hello(String message) {
      this.message = message;
   }
 
   public void setMessage(String message) {
      this.message = message;
   }
 
   public String getMessage() {
      return message;
   }
 
   public void sayHello() {
      System.out.println(message);
   }
}

実行時のVM argument

実行時のVM argumentに以下を指定する
-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=1767 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false