I am a kite, the public number “ancient kite”, a both depth and breadth of programmers encourage division, a plan to write poetry but write up the code of rural code farmers! Articles will be included in JavaNewBee, and there will be a Java back-end knowledge map, which will cover the path from small white to big cow.
If you haven’t done it before, it’s like, “What the hell is this? Why? What’s the use?” .
You may not know it, but you’ve certainly been exposed to it at some point.
If you use Spring Boot, for example, if you use Spring Boot, it uses JMX. For example, if you use JConsole or VisualVM, they also use JMX.
Above, you can make such a JVM monitor using JMX.
Isn’t that interesting?
Above is the interface I implemented myself and below is the interface for JConsole and VisualVM.
How they use JMX, step by step.
What is a JMX
JMX stands for Java Management Extensions, which translates to Java Management Extensions for managing and monitoring Java programs. The most commonly used is monitoring and management of the JVM, such as JVM memory, CPU usage, thread count, garbage collection, and so on. In addition, it can be used to dynamically change the log level. For example, log4j supports JMX to dynamically change the log level of online services. Most of all, it is used to make various monitoring tools, such as Spring Boot Actuator, JConsole and VisualVM mentioned at the beginning of the article.
JMX is not only a standard, a specification, but also an interface and a framework of Java management system. There are standards and specifications to allow developers to customize their own extensions, and as a framework, the JDK already provides common functionality, especially for monitoring and managing the JVM.
The diagram above shows a simple diagram of the JMX architecture, which means that the management system can manage various resources through JMX.
A management system can be understood as a management client, such as the aforementioned JConsole, VisualVM, and Metrics, the well-known Java monitoring toolkit, or your own client implemented through the JMX interface. Various resources such as system configuration, JVM metrics, etc., or resources specific to your own project.
Here’s the thing, JMX
The architecture diagram expands the above architecture diagram, and the following is a brief overview from the bottom up.
MBean
JMX delivers messages through a variety of Managed Beans, which are what we call Java beans, but are called MBeans because they are special. Since it is a Bean, it contains properties and methods that allow outsiders to obtain the state of managed resources and manipulate the behavior of the MBean. There are four types of MBeans in JMX: Standard MBeans, Dynamic MBeans, Open MBeans, and Model MBeans. The JDK provides mbeans mainly in the java.lang.management and Javax. management packages. If you look at VisualVM, you can see a lot of familiar images, such as memory-related, thread-related, which is what we see in VisualVM.
To be honest, I don’t care too much about the differences between these mBeans, but I’ll give you a brief overview.
Standard MBeans are just plain Java beans, and they are the simplest and most commonly used type of JMX. It is mainly in the java.lang.management package.
Dynamic MBeans are actually a compromise, because some already exist and converting them to standard MBeans is laborious and impractical, hence the Dynamic MBeans. The Dynamic of an interface in the javax.mail. Management. DynamicMBean here, it defined some interface methods, such as Dynamic gain attributes and set properties, etc.
There are two other types of MBeans: Open mBeans and Model MBeans, which are also, in fact, dynamic MBeans.
The only difference between Open MBeans and other dynamic MBeans is that The former for limits on the parameters and return values of its public interface — only basic types or javax.mail. Management openmbean package ArrayType, CompositeType, TarbularType type, etc. This is mainly due to the distribution of management systems, and it is likely that the remote management system or even the MBServer layer will not have special classes in the MBean interface.
MBeanServer
MBeanServer is responsible for managing Mbeans. Generally, a JVM has only one MBeanServer. All Mbeans need to be registered with MBeanServer and provide services externally through MBeanServer. General use ManagementFactory. GetPlatformMBeanServer () method gets the current MBeanServer within the JVM.
Adapters and connectors
Once the written MBeans are registered with the MBeanServer, the functionality is ready. Adapters and connectors are ways to open up these capabilities. The HTTP protocol adapter, for example, exposes functionality to HTTP so that it can be used in the browser. However, THE JDK only provides the implementation standard of the adapter, and there is no specific implementation. HtmlAdaptorServer is more commonly used, which requires the support of jmXTools.jar package.
Connectors are most commonly used by various clients, and the DEFAULT connector provided by the JDK is the RMI connector, which is used by JConsole and VisualVM.
Implement and use an MBean
Although Java provides standards and rules for implementing MBeans, you rarely need to develop mBeans in normal times. The vast majority of developers are exposed only to using JDK or third party defined Mbeans, and even if third parties have implemented Mbeans, it is very rare. We know of Tomcat and Spring Boot Actuator.
Define MBean interfaces and entity classes
/ / interface
public interface UserMBean {
String getName(a);
String getPassword(a);
String getPhone(a);
void say(a);
}
Copy the code
public class User implements UserMBean {
@Override
public String getName(a) {
return "The kite";
}
@Override
public String getPassword(a) {
return "Password not visible";
}
@Override
public String getPhone(a) {
return "18900000000";
}
@Override
public void say(a) {
System.out.println("Hello JMX");
}
}
Copy the code
Entity classes need to inherit from the MBean interface class, and the interface class is named “entity class name +MBean”, which is a fixed rule.
Register the defined MBeans with MBeanServer
public static void main(String[] args) throws Exception {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName userName = new ObjectName("FengZheng:type=customer,name=customerUserBean");
server.registerMBean(new User(), userName);
try {
// This step is very important. Register a port and bind the URL for the client to connect to JMXConnectorServer via RMI
LocateRegistry.createRegistry(8999);
// The end of the URL path is optional, but if you want to use Jconsole for connection, you must use jmxRMi
JMXServiceURL url = new JMXServiceURL
("service:jmx:rmi:///jndi/rmi://localhost:8999/jmxrmi");
JMXConnectorServer jcs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
System.out.println("begin rmi start");
jcs.start();
System.out.println("rmi start");
} catch (RemoteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Thread.sleep(60 * 60 * 1000);
}
Copy the code
ManagementFactory. GetPlatformMBeanServer () gets the current JVM MBeanServer, ObjectName is the only label, an an MBeanServer there cannot be repeated. The complete format is “Custom namespace :type= custom type,name= custom name”. Of course you can just declare type and not name.
Use JConsole to view
JConsole is a built-in JDK tool. You can start it in the bin directory of ${JAVA_HOME}. After starting, find the process of the main method that was started in the previous step in the local process.
At the top of JConsole are the Memory, Threads, Classes, and so on tabs. Click on the last MBean to see all the MBeans defined by the current JVM. You can see the system-defined MBean, as well as the MBean we just defined.
Click the property to view the property value on the right side, and under the operation menu item, you can see the method we defined and call it.
Connect in RMI mode
RMI is generally used to connect to remote services, although local processes can also be used. This is also the first step in implementing a connection to a remote service client. When registering mBeans, did you notice that after registering mBeans, there is a large section of code that is used to enable RMI connection? Enable port 8999 as RMI access port, and then the client can connect with fixed connection string.
Connection string format of the service: JMX: rmi: / / / jndi/rmi: / / host: port/jmxrmi
public class Client {
public static void main(String[] args) throws IOException, Exception, NullPointerException {
String jmxUrl = "service:jmx:rmi:///jndi/rmi://localhost:8999/jmxrmi";
monitor(jmxUrl);
}
public static void monitor(String url) throws Exception{
JMXServiceURL jmxServiceURL = new JMXServiceURL
(url);
JMXConnector jmxc = JMXConnectorFactory.connect(jmxServiceURL, null);
MBeanServerConnection msc = jmxc.getMBeanServerConnection();
String[] domains = msc.getDomains();
for (String domain : domains) {
System.out.println(domain);
}
}
}
Copy the code
According to the connection string to obtain a JMXServiceURL object first, then by JMXConnectorFactory. The connect method obtaining JMXConnector, Get the MBeanServerConnection via getMBeanServerConnection. Then you can get all the MBeans. GetDomains is the method to get all the namespaces, i.e. “FengZheng” we defined above, JMImplementation, java.lang, etc., and that’s what we see in JConsole.
Did a web version of the simple monitoring
In order to learn more about JMX, the first step was to show all the MBeans and properties and start exporting them to the console, but it didn’t work well. The content was too long and not intuitive, so I added a Tree structure on the Web side. And then along came the discovery that with a few tweaks it could be used as a web version of the simple monitoring end.
This tool has only been tested in a hotspot JVM 8 environment. Supports viewing local and remote JVM real-time monitoring.
React 16 + Antd + Yarn at the front end and Spring Boot + Java 1.8 at the back end. You can go to the Github repository README page for details. An online preview version is provided, with the source address and how to use the online version.
Support for local and remote JVM linking.
Tree display of all MBeans and display of properties and operations.
Real-time display of JVM health
The functions are as follows:
-
A display of all MBeans;
-
Display of system information, including memory usage, CPU usage, etc.
-
JVM parameters, including command line parameters and systemProperties;
-
Real-time line charts for CPU, Heap, Metaspace, class loading, threads;
-
Type of garbage collector and number of collections;
Here’s how to use JMX in combination with these sections.
An acquisition
Mbeans themselves exist in this hierarchy, just as mBeans in various tools are presented in a tree.
Mbeans are contained in the Domain, which is a set of independent Spaces in which objectNames of various types and names can be defined. Like the custom one from the previous JMX article.
ObjectName lets you get various MBean information, including properties, operations, and notifications.
Some attributes are simple data types, such as int, long, double, String, and others are more complex. For example com. Sun. Management: the attribute of type = HotSpotDiagnostic DiagnosticOptions is javax.management.openmbean.Com positeData type. And the properties of the data type is javax.mail management openmbean. TabularData. These have to be dealt with separately.
The commonly used an
Some metrics are used by monitoring, such as memory, CPU, heap space, threads, and class-loading related MBeans.
The JDK provides a ManagementFactory, which helps us easily get commonly used MBeans. You can find this class in the java.lang.management package to look at the comments and code.
OperatingSystemMXBean
You can obtain information about the operating system, such as the machine name, memory usage, and CPU usage.
Get through ManagementFactory. GetOperatingSystemMXBean () way.
RuntimeMXBean
You can get information about the current JVM, including JVM parameters and JVM-related system parameters.
Can through the ManagementFactory. GetRuntimeMXBean () way to get.
MemoryMXBean
You can get the memory usage of the current JVM, both heap and non-heap.
Can through the ManagementFactory. GetMemoryMXBean ()
ThreadMXBean
Gets JVM thread usage, including active threads, daemons, thread spikes, and so on.
Can through the ManagementFactory. GetThreadMXBean ().
ClassLoadingMXBean
Gets JVM classes loaded, unloaded, and so on.
Can through the ManagementFactory. GetClassLoadingMXBean ().
GarbageCollectorMXBean
Gets information about the JVM garbage collector, including which garbage collector is used, the number of collections, and so on.
By ManagementFactory. GetGarbageCollectorMXBeans (), note that get here is a collection, because the garbage collector is divided into old age and new generation or two.
In addition to the above few commonly used MBeans, there are many others. Some are already provided in the ManagementFactory class, and many more need to be fetched yourself via ObjectName.
The source code to the
Send a picture does not send a kind,……. . Of course not to do that sort of thing.
The source code is available on Github at github.com/huzhicheng/… README has details on how to use it. Since the JVM varies from operating system to operating system and Windows, Mac, and Linux are not universal, no release JAR package is available. For example, Linux, the Mac I developed with, is different from the experience environment and needs to be compiled separately. To use it, you need to download the source code, compile it locally, and run it.
Interested might as well try, welcome clap brick.
Strong man wait, first give a praise bar, always white piao, the body can not bear!
Public account “ancient kite”, Java developer, full stack engineer, known as late prince, bug killer, good at solving problems. A programmer with both depth and breadth of encouragement teacher, originally intended to write poetry but wrote up the code of rural code farmers! Stick to original dry goods output, you can choose to pay attention to me now, or read a historical article and then pay attention to it. Long press the QR code to follow, become excellent with me!