import java.io.IOException; import java.lang.reflect.Method; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import javax.management.InstanceNotFoundException; import javax.management.JMException; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.MBeanServerInvocationHandler; import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.QueryExp; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; public class ManagementContext implements Service { private MBeanServer beanServer; private final AtomicBoolean started = new AtomicBoolean(false); private String connectorHost = "localhost"; private int connectorPort = 1099; private final AtomicBoolean connectorStarting = new AtomicBoolean(false); public ManagementContext() { this(null); } public ManagementContext(MBeanServer server) { this.beanServer = server; } @Override public void start() throws Exception { if(started.compareAndSet(false, true)) { if(connectorHost == null) { connectorHost = "localhost"; } getMBeanServer(); if(connectorServer != null) { try { if(getMBeanServer().isRegistered(namingServiceObjectName)) { getMBeanServer().invoke(namingServiceObjectName, "start", null, null); } } catch(Throwable ignore) { // log exception info } } Thread thread = new Thread("JMX connector") { public void run() { try { JMXConnectorServer server = connectorServer; if(started.get() && server != null) { System.out.println("Starting JMXConnectorServer..."); connectorStarting.set(true); try { server.start(); } finally { connectorStarting.set(false); } } } catch(IOException e) { e.printStackTrace(); } finally { // } } }; thread.setDaemon(true); thread.start(); } } protected MBeanServer getMBeanServer() { if(this.beanServer == null) { this.beanServer = findMBeanServer(); } return beanServer; } private boolean useMBeanServer = true; private boolean createMBeanServer = true; private boolean findTigerMbeanServer = true; private boolean createConnector = true; protected synchronized MBeanServer findMBeanServer() { MBeanServer result = null; try { if(useMBeanServer) { if(findTigerMbeanServer) { result = findTigerMBeanServer(); } if(result == null) { List<MBeanServer> list = MBeanServerFactory.findMBeanServer(null); if(list != null && list.size() > 0) { result = list.get(0); } } if(result == null && createMBeanServer) { result = createMBeanServer(); } } } catch(NoClassDefFoundError e) { // log exception e.printStackTrace(); } catch (Throwable e) { // log info e.printStackTrace(); } return result; } private static final String DEFAULT_DOMAIN = "org.fantasy"; private String jmxDomainName = DEFAULT_DOMAIN; private boolean locallyCreateMBeanServer; protected MBeanServer createMBeanServer() throws MalformedObjectNameException, NullPointerException, IOException { MBeanServer mbeanServer = MBeanServerFactory.createMBeanServer(jmxDomainName); locallyCreateMBeanServer = true; if(createConnector) { createConnector(mbeanServer); } return mbeanServer; } public MBeanServer findTigerMBeanServer() { String name = "java.lang.management.ManagementFactory"; Class<?> type = loadClass(name, ManagementContext.class.getClassLoader()); if(type != null) { try { Method method = type.getDeclaredMethod("getPlatformMBeanServer", new Class[0]); if(method != null) { Object answer = method.invoke(null, new Object[0]); if(answer instanceof MBeanServer) { if(createConnector) { createConnector((MBeanServer)answer); } return (MBeanServer)answer; } else { // log info } } else { // log info } } catch (Exception e) { // log exception } } else { // log info } return null; } private Registry registry; private ObjectName namingServiceObjectName; private int rmiServerPort; private String connectorPath = "/jmxrmi"; private Map<String, ?> environment; private JMXConnectorServer connectorServer; private void createConnector(MBeanServer mbeanServer) throws IOException, MalformedObjectNameException, NullPointerException { if(registry == null) { registry = LocateRegistry.createRegistry(connectorPort); } namingServiceObjectName = ObjectName.getInstance("naming:type=rmiregistry"); String rmiServer = ""; if(rmiServerPort != 0) { rmiServer = "" + getConnectorHost() + ":" + rmiServerPort; } /** service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi */ String serviceURL = "service:jmx:rmi://" + rmiServer + "/jndi/rmi://" +getConnectorHost()+":" + connectorPort + connectorPath; JMXServiceURL url = new JMXServiceURL(serviceURL); connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, mbeanServer); } public int getConnectorPort() { return connectorPort; } public String getConnectorHost() { return connectorHost; } private final Map<ObjectName, ObjectName> registeredMBeanNames = new ConcurrentHashMap<ObjectName, ObjectName>(); public void stop() throws Exception { if(started.compareAndSet(true, false)) { MBeanServer mbeanServer = getMBeanServer(); if(mbeanServer != null) { for (Map.Entry<ObjectName, ObjectName> entry : registeredMBeanNames.entrySet()) { ObjectName actualName = entry.getValue(); if (actualName != null && beanServer.isRegistered(actualName)) { mbeanServer.unregisterMBean(actualName); } } } registeredMBeanNames.clear(); JMXConnectorServer server = connectorServer; connectorServer = null; if(server != null) { if(!connectorStarting.get()) { server.stop(); } } if(namingServiceObjectName != null && getMBeanServer().isRegistered(namingServiceObjectName)) { getMBeanServer().invoke(namingServiceObjectName, "stop", null, null); getMBeanServer().unregisterMBean(namingServiceObjectName); } namingServiceObjectName = null; if(locallyCreateMBeanServer && beanServer != null) { List<MBeanServer> list = MBeanServerFactory.findMBeanServer(null); if(list != null && !list.isEmpty() && list.contains(beanServer)) { MBeanServerFactory.releaseMBeanServer(mbeanServer); } } beanServer = null; } if(registry != null) { UnicastRemoteObject.unexportObject(registry, true); registry = null; } } private static Class<?> loadClass(String name, ClassLoader loader) { try { return loader.loadClass(name); } catch (ClassNotFoundException e) { try { return Thread.currentThread().getContextClassLoader().loadClass(name); } catch (ClassNotFoundException e1) { return null; } } } public ObjectName createCustomComponentMBeanName(String type, String name) { ObjectName result = null; String tmp = jmxDomainName + ":" + "type=" + sanitizeString(type) + ",name=" + sanitizeString(name); try { result = new ObjectName(tmp); } catch (MalformedObjectNameException e) { e.printStackTrace(); // exception } return result; } public Object getAttribute(ObjectName name, String attribute) throws Exception { return getMBeanServer().getAttribute(name, attribute); } public Object newProxyInstance(ObjectName objectName, Class<?> interfaceClass, boolean notificationBroadcaster) { return MBeanServerInvocationHandler.newProxyInstance(getMBeanServer(), objectName, interfaceClass, notificationBroadcaster); } public ObjectInstance registerMBean(Object bean, ObjectName name) throws Exception { ObjectInstance result = getMBeanServer().registerMBean(bean, name); this.registeredMBeanNames.put(name, result.getObjectName()); return result; } public Set<ObjectName> queryNames(ObjectName name, QueryExp query) throws Exception { if (name != null) { ObjectName actualName = this.registeredMBeanNames.get(name); if(actualName != null) { return getMBeanServer().queryNames(actualName, query); } } return getMBeanServer().queryNames(name, query); } private static String sanitizeString(String in) { String result = null; if (in != null) { result = in.replace(':', '_'); result = result.replace('/', '_'); result = result.replace('\\', '_'); } return result; } public ObjectInstance getObjectInstance(ObjectName name) throws InstanceNotFoundException { return getMBeanServer().getObjectInstance(name); } public void unregisterMBean(ObjectName name) throws JMException { ObjectName actualName = this.registeredMBeanNames.get(name); if ( beanServer != null && actualName != null && beanServer.isRegistered(actualName) && this.registeredMBeanNames.remove(name) != null ) { beanServer.unregisterMBean(actualName); } } public static void main(String[] args) throws Exception { ManagementContext managementContext = new ManagementContext(); managementContext.start(); ObjectName objectName = managementContext.createCustomComponentMBeanName("20160113", "1507"); Hello hello = new Hello(); ObjectInstance objectInstance = managementContext.registerMBean(hello, objectName); objectInstance.getClassName(); String name = (String)managementContext.getAttribute(objectName, "Name"); System.out.println(name); Set<ObjectName> names = managementContext.queryNames(objectName, null); for(ObjectName oName : names) { System.out.println(oName); } // managementContext.stop(); Thread.sleep(Long.MAX_VALUE); } }
public interface Service { public void start() throws Exception; public void stop() throws Exception; }
相关推荐
总的来说,JMX是一个强大的工具,它让开发者能够轻松地对Java应用进行监控和管理,通过暴露管理接口,使得运维人员可以在运行时动态调整应用程序的行为,提高系统的可维护性和稳定性。通过学习和实践JMX,开发者可以...
本篇文章将深入探讨JMX的核心概念、功能及如何通过一个小例子来理解和使用JMX。 **1. JMX核心概念** - **MBean(Managed Beans)**: MBean是JMX中最基本的管理单元,它是Java对象,代表可管理的资源或服务。MBean...
在这个"一个jmx的小例子"中,我们很可能是通过编写Java代码来创建和操作MBeans,然后使用Eclipse这样的集成开发环境(IDE)来运行示例。Eclipse本身并不直接支持JMX,但可以通过安装插件如JConsole或VisualVM来辅助...
对于初学者,这个"最简单JMX例子"将展示如何创建一个简单的MBean,如何在Eclipse这样的集成开发环境中配置和运行,以及如何通过标准的JMX客户端工具进行交互。通过学习这个例子,你可以理解JMX的基本结构和用法,为...
标题和描述均提到了“jmx第一个学习例子”,这标志着文章旨在引导读者通过一个实践性的示例理解Java Management Extensions(JMX)的基础概念和技术。JMX作为一项由Sun Microsystems(现Oracle)提出的技术,用于...
压缩包里有:http_sample.jmx,JMeterPlugins-Extras.jar,JMeterPlugins-Standard.jar,ServerAgent-2.2.1.zip 1:安装Java8环境 2:安装apache-jmeter-3.1 ...5:启动Jmeter,修改jmx的配置,运行脚本。
通常,我们需要定义一个bean,该bean实现了MBean接口或者使用了`@ManagedResource`注解,使得它成为JMX管理的对象。例如,你可能会看到如下配置: ```xml <jmx:managed /> ``` 这里的`jmx:managed`标签表示将`...
书中提供了几个典型的例子,兼顾各种开发平台,这些例子的代码稍作修改就可以直接应用于项目开发之中,代码源文件可以从图灵网站下载。本书内容广泛且深入,同时适用于各个层次的Web应用开发人员。
这个压缩包中的例子很可能是创建了一个简单的Spring应用,并且配置了JMX支持,展示如何将Spring的bean暴露为MBeans进行管理和监控。通过研究这些示例,新人可以更好地理解JMX和Spring如何协同工作,提升他们的Java...
Java Management Extensions(JMX)是Java平台上的一个标准,它提供了管理和监控应用程序、操作系统和网络设备的能力。在本文中,我们将深入探讨JMX的核心概念、关键组件以及如何使用所提供的JAR和文档来学习和实践...
在这个入门例子中,我们将深入探讨JMX的核心概念以及如何通过提供的源码实现一个简单的JMX应用。 首先,`HelloAgent.java`通常是实现JMX代理的类,这个代理负责注册MBeans(Managed Beans),这是JMX中的核心组件。...
Java Management Extensions(JMX)是Java平台上的一个标准管理框架,它允许开发人员创建、注册和管理名为MBeans(Managed Beans)的对象,这些对象代表了系统、应用程序或服务的可管理资源。通过JMX,我们可以远程...
让我们通过一个简单的例子来了解JMX的工作流程: 1. 首先,定义一个MBean接口,比如`HelloWorldMBean`,包含一个返回字符串的属性`greeting`和一个输出问候的`sayHello`操作。 ```java public interface ...
Java Management Extensions(JMX)是Java平台上的一个标准技术,用于管理和监控应用程序、服务和设备。JMX允许开发者创建管理接口,以便对运行时的组件进行动态监控和管理。在这个"jmx_examples.rar"压缩包中,包含...
在上述例子中,我们创建了一个 JMX Agent,并将其绑定到本地的 RMI 端口 9999 上。这种配置虽然能够实现 JMX 监控和管理功能,但存在安全漏洞。默认情况下,这个 JMX Agent 的 RMI 端口是不加密的,并且没有进行身份...
JMX(Java Management Extensions)是Java平台上的一个标准管理框架,用于监控和管理应用程序、服务、设备以及其他系统资源。这个框架允许开发人员创建可管理的组件,并通过标准接口暴露其管理功能。《JMX技术介绍》...
在JDK1.3和1.4版本中,JMX是作为一个单独的下载包提供的,需要从Sun Microsystems的官方网站下载jmx-1_2_1-ri.zip和jmx_remote-1_0_1_03-ri.zip两个ZIP文件,并将包含的JAR文件添加到classpath。而在JDK5.0及更高...
在本章中,我们将通过一个例子来说明如何使用动态MBean来管理Jini服务的广告方式。这个MBean将负责改变Jini服务在网络中的自我呈现方式。此外,我们还将创建一个动态MBean的超类,为未来资源的元数据描述提供代码...