JMX是一種JAVA的正式規範,它主要目的是讓程序有被管理的功能。html
那麼怎麼理解所謂的「被管理」呢?試想你開發了一個軟件(如WEB網站),它是在24小時不簡斷運行的,那麼你可能會想要「監控」這個軟件的運行狀況,好比收到了多少數據,有多少人登陸等等。或者你又想「配置」這個軟件,好比如今訪問人數比較多,你想把數據鏈接池設置得大一些;天天的UV、PV是多少;又或者在業務高峯的期間,你想對接口進行限流,就必須去修改接口併發的配置值。java
應用場景:中間件軟件WebLogic的管理頁面就是基於JMX開發的,而JBoss則整個系統都基於JMX構架。apache
對於一些參數的修改,網上有一段描述仍是比較形象的:緩存
一、程序初哥通常是寫死在程序中,到要改變的時候就去修改代碼,而後從新編譯發佈。架構
二、程序熟手則配置在文件中(JAVA通常都是properties文件),到要改變的時候只要修改配置文件,但仍是必須重啓系統,以便讀取配置文件裏最新的值。併發
三、程序好手則會寫一段代碼,把配置值緩存起來,系統在獲取的時候,先看看配置文件有沒有改動,若有改動則從新從配置裏讀取,不然從緩存裏讀取。app
四、程序高手則懂得物爲我所用,用JMX把須要配置的屬性集中在一個類中,而後寫一個MBean,再進行相關配置。另外JMX還提供了一個工具頁,以方便咱們對參數值進行修改。dom
讓開發者和管理者能夠獲取程序運行的狀態以及動態的修改程序的相關配置。工具
SUN依據這個規範在JDK提供了JMX接口,而根據這個接口的實現則有不少種,好比Weblogic的JMX實現、MX4J、JBoss的JMX實現。網站
咱們常用的JDK中SUN公司的實如今java.lang.management包下。
MBean 即 managed beans 被管理的Beans
從圖中咱們能夠看到,JMX的結構一共分爲三層:
一、基礎層:主要是MBean,被管理的資源。
MBean分爲以下四種,我接下來主要介紹standard MBean
類型描述standard MBean這種類型的MBean最簡單,它能管理的資源(包括屬性,方法,時間)必須定義在接口中,而後MBean必須實現這個接口。它的命名也必須遵循必定的規範,例如咱們的MBean爲Hello,則接口必須爲HelloMBean。dynamic MBean必須實現javax.management.DynamicMBean接口,全部的屬性,方法都在運行時定義open MBean此MBean的規範還不完善,正在改進中model MBean與標準和動態MBean相比,你能夠不用寫MBean類,只需使用javax.management.modelmbean.RequiredModelMBean便可。RequiredModelMBean實現了ModelMBean接口,而ModelMBean擴展了DynamicMBean接口,所以與DynamicMBean類似,Model MBean的管理資源也是在運行時定義的。與DynamicMBean不一樣的是,DynamicMBean管理的資源通常定義在DynamicMBean中(運行時才決定管理那些資源),而model MBean管理的資源並不在MBean中,而是在外部(一般是一個類),只有在運行時,才經過set方法將其加入到model MBean中。後面的例子會有詳細介紹
二、適配層:MBeanServer,主要是提供對資源的註冊和管理。
三、接入層:提供遠程訪問的入口。
JMX超詳細解讀 - 冬瓜蔡 - 博客園 這篇博客詳細介紹了三種使用JMX的方式,下面我提供一下本身實現的例程
import java.io.IOException; import java.lang.management.ManagementFactory; import java.rmi.registry.LocateRegistry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import com.sun.jdmk.comm.HtmlAdaptorServer; public class ApplicationServer { private static HtmlAdaptorServer adaptorServer = null; private static javax.management.remote.JMXConnectorServer cs = null; private static Logger logger = null; private static ExecutorService cachedExecutors = null; private static void initExecutor() { cachedExecutors = Executors.newFixedThreadPool(2); } private static void exitExecutor() { cachedExecutors.shutdown(); } public static void execute(final Runnable runnable) { cachedExecutors.execute(runnable); } private static void initLogger() { System.out.println("configuring log4j with log4j.xml"); DOMConfigurator.configure("log4j.xml"); logger = Logger.getLogger("root"); } private static void initHtmlJMX() throws Exception { MBeanServer server = MBeanServerFactory.createMBeanServer(); ObjectName helloName = new ObjectName("jmx:name=HelloWorld"); server.registerMBean(new Hello(), helloName); ObjectName adapterName = new ObjectName("HelloAgent:name=htmladapter,port=8081"); adaptorServer = new HtmlAdaptorServer(); server.registerMBean(adaptorServer, adapterName); adaptorServer.start(); logger.info("start jmx html server"); } private static int initProtogenesisJMX() throws Exception { String port1Str = System.getProperty("com.jmxport1"); String port2Str = System.getProperty("com.jmxport2"); if (port1Str == null || port2Str == null) { logger.error("jmx端口未經過系統屬性設置"); return -1; } final int port1 = Integer.valueOf(port1Str); final int port2 = Integer.valueOf(port2Str); System.setProperty("java.rmi.server.randomIDs", "true"); try { LocateRegistry.createRegistry(port2); } catch (java.rmi.server.ExportException ex) { logger.error("err", ex); return -1; } MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); java.util.HashMap<String, Object> env = new java.util.HashMap<String, Object>(); env.put("jmx.remote.x.password.file", "jmxremote.password"); env.put("jmx.remote.x.access.file", "jmxremote.access"); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://127.0.0.1:" + port1 + "/jndi/rmi://127.0.0.1:" + port2 + "/jmxrmi"); cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs); try { cs.start(); } catch (java.net.BindException ex) { logger.error("端口已被佔用", ex); return -2; } return 0; } public static void exitHtmlJMX() { adaptorServer.stop(); } public static void exitProtogenesisJMX() throws IOException { cs.stop(); } public static void init() throws Exception { initLogger(); // initHtmlJMX(); initProtogenesisJMX(); initExecutor(); } public static void exit() throws IOException { //exitHtmlJMX(); exitProtogenesisJMX(); exitExecutor(); } public static void main(String[] args) throws Exception { System.setProperty("com.jmxport1", String.valueOf(7000)); System.setProperty("com.jmxport2", String.valueOf(7001)); init(); MBeanServer server = java.lang.management.ManagementFactory.getPlatformMBeanServer(); ObjectName helloName = new ObjectName("jmxBean:name=stopper"); server.registerMBean(new Stopper(), helloName); } public interface StopperMBean { void stop() throws IOException; } public static class Stopper implements StopperMBean { public void stop() throws IOException { ApplicationServer.exit(); } } }
import java.text.SimpleDateFormat; import java.util.HashMap; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; public class JMXClient { /** * * @param args * host port username password bean name method ...params * @throws Exception */ public static void main(String[] args) throws Exception { if ((args.length < 6) || (args.length % 2 != 0)) { logErr("params error"); return; } final String host = args[0]; final int rmiPort = Integer.valueOf(args[1]).intValue(); final String username = args[2]; final String password = args[3]; final ObjectName objectName = new ObjectName(args[4]); final String methodName = args[5]; final HashMap<String, String[]> jmxParamsHashMap = new HashMap<String, String[]>(); final String[] usernameAndPassword = { username, password }; jmxParamsHashMap.put("jmx.remote.credentials", usernameAndPassword); final String serviceUrl = new StringBuilder().append("service:jmx:rmi:///jndi/rmi://").append(host).append(":") .append(rmiPort).append("/jmxrmi").toString(); final JMXServiceURL jmxServiceURL = new JMXServiceURL(serviceUrl); final JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceURL, jmxParamsHashMap); if (jmxConnector == null) { logErr(new StringBuilder().append("connect to jmx failed, url=").append(jmxServiceURL).toString()); return; } log(new StringBuilder().append("JMXConnector=").append(jmxConnector.toString()).toString()); Object[] paramsValue = null; String[] paramsClassName = null; final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection(); final Object localObject = mBeanServerConnection.invoke(objectName, methodName, paramsValue, paramsClassName); log(new StringBuilder().append("invoke method success, name=").append(objectName).append(", operation=") .append(methodName).append(", retvalue=").append(localObject == null ? "void" : localObject.toString()) .toString()); } static void log(String paramString) { final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss : "); final StringBuilder sBuilder = new StringBuilder(); sBuilder.append(simpleDateFormat.format(Long.valueOf(System.currentTimeMillis()))); sBuilder.append(paramString); System.out.println(sBuilder.toString()); } static void logErr(String paramString) { final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss : "); final StringBuilder sBuilder = new StringBuilder(); sBuilder.append(simpleDateFormat.format(Long.valueOf(System.currentTimeMillis()))); sBuilder.append(paramString); System.err.println(sBuilder.toString()); } }