Detailed explanation of Lifecycle in Tomcat (source code reading) Understand the introduction and simple use of JMX

Understand the introduction and simple use of JMX

Original  2017/04/30 23:46:08
  • 5509

Recently, I need to add some functions to the project. I want to integrate an open source project. Although it is integration, I feel that there is not much to check with the development. The coding style and design method of this open source project must be consistent with our project, which involves When it comes to application monitoring and management, it is inevitable to use JMX. I have a brief understanding of JMX before, but I have no motivation to deeply understand its principles and coding. Due to the needs of the project, this time I will summarize JMX in depth. About monitoring The content, I wrote an understanding of the SNMP protocol for system monitoring before , which is purely a popular science article, and has not been implemented by programming. But in fact, monitoring is very important for a software or application. There is a series of articles on InfoQ to introduce the construction of monitoring system. Let’s talk about monitoring (1): what is worth monitoring and the choice of monitoring indicators . If you want to know more about it You can take a look.

Going back to JMX, before writing this article, I found a lot of related articles on the Internet, and I was at a loss when I read it, so in this article, I want to put my understanding in plain language.

Introduction to JMX

The so-called JMX is the abbreviation of Java Management Extensions. From the official document, it is a framework, which is the same as JPA and JMS, and is no different from Spring and Hibernate that we usually use. It is to put together the problems and solutions of all aspects involved in monitoring and management, and unify the design to provide services for users to call. Its API is in the following two places:

  • java.lang.management:
  • javax.management.*:包括javax.management.loading、javax.management.modelmbean等;

Resource management

Since JMX is about monitoring and management, what do they include? The core is a series of operations for resources . What is a resource? In my understanding, as long as it is a resource that can help your activities and the normal operation of the system , then for an application, a resource can be:

  • hardware equipment
  • computer network
  • operating system
  • run server

There are far more things that can be called resources, such as the people and developers who run them, aka human resources, etc. What we need to do is to monitor and manage them. Monitoring is to detect problems in time, so that we can propose correct solutions in time to avoid losses; management is to prevent problems from occurring, but also to enable resources to be used effectively. maximize profits. Aspects to consider when monitoring and managing are as follows:

  • Monitor the operation of hardware and platforms: including servers and operating systems;
  • Reasonable allocation of resources: such as whether the memory configuration is reasonable, and whether the CPU is powerful enough;
  • Collect the running situation of the application: for example, how many visits are there, whether the response time is fast enough, and which region has the largest number of visitors;
  • When the application is abnormal, it can locate the problem in time: this is one of the cores of monitoring;

How were these problems solved before JMX? We can think about it, each resource, the corresponding manufacturer has its own monitoring and management components, then if you want to change a configuration globally, you may design a lot of monitoring components, which is a headache to think about! Our goal is to centralize management and monitoring , which obviously couldn't be done in the previous environment, but it is possible through JMX, which is why the person who proposes the standard is the one who has the most say! All of the above are well supported by JMX.

JMX terminology

Each framework has its own professional terms, which can show the design ideas of the framework to a certain extent, such as Spring's bean, JPA's Entity, and so on. The entire architecture of JMX can also be seen from the terms involved in JMX:

  • Manageable resource : As I said above, as long as it can help your activities and the normal operation of the system, it can be regarded as a resource, which can be hardware or application, as long as it can be described by Java classes;

  • Management component (MBean, managed bean) : From the perspective of resources, it is a description of an abstract resource. For example, if the resource is a database, the management component can provide some description information of the database, such as the operation of the database server. Address, port, type, and maximum number of connections, etc., but this class must meet the requirements set forth in the JMX specification, such as naming rules and implementation standards, similar to JavaBean. Since the management component is an abstraction of resources, the management application is directly oriented to the MBean, which means that the MBean will be exposed to the management application for operation and access. There are also several types of MBeans through the attributes and methods provided in the MBean. If there is no special description, this article refers to Standard MBean, and its specific use is explained in the coding section below;

  • Management component server (MBean Server) : In simple terms, it is a container used to hold and manage a group of MBeans. It is the core of the entire JMX management environment. Since there are many MBeans, it must provide a mechanism To distinguish each MBean, this is the registration mechanism. Each MBean added to the MBean Server must provide an ObjectName to distinguish each other when it is registered. The MBean Server uses this ObjectName to find each MBean. In JMX, it is through the ObjectName class. Provide a unique identifier for each MBean, which consists of two parts:

    • Domain name: This domain name is usually the same as the name of the MBean Server to be registered, so that MBeans in different MBean Servers can be distinguished according to function modules;
    • List of key-value pairs: It is used to uniquely identify the MBean, and also provides information about the MBean in the following form: HelloAgent:name=helloWorld; the attributes in it are not necessarily the attributes of the real MBean, it is only required to be compatible with other MBeans It can be uniquely identified when comparing, and each ObjectName must have at least one attribute;

    When the ObjectName is repeated, javax.management.InstanceAlreadyExistsException will be thrown during registration, which will be emphasized in the later coding stage;

  • JMX Agent (JMX Agent) : It provides a series of services to manage a series of MBeans, which is the container of the MBean Server. JMX agents provide some services, including creating relationships between MBeans, dynamically loading classes, simple monitoring services, and timers; agents can have a series of protocol adapters (Protocol adapters) and connectors (connectors), protocol adapters and connectors are also Java classes, usually MBeans, these adapters and connectors exist to provide transfer functions, so that different protocols can be used remotely, and the client can connect with this proxy, which can internally map to an external protocol or Expose the proxy to the remote connection, which means that the JMX proxy can be used by a series of different management protocols and tools, which is essentially a manifestation of the plug-in architecture, reflecting the idea of ​​pluggability;

  • Protocol adapters and connectors : Protocol adapters and connectors are objects in the JMX Agent that expose the agent to different management applications and protocols. This is similar to the drivers for different databases. Each database has Its own set of protocols to contact, in order to maintain the connection, it is necessary to associate between the JDBC application and the database server through different drivers. A JMX Agent can have any number of adapters and connectors; they are also MBeans;

  • Notification (Notification): Notification is proposed by MBeans and MBean Server, which encapsulates specific events and corresponding data. Other MBeans or Java objects can be registered as listeners to receive these notifications, which is actually the application of the observer design pattern in JMX;

Architecture of JMX

The architecture of JMX is component-based and is designed in three layers:

  • Distributed layer : Contains components that allow management applications to interact with JMX Agents. Once the connection with JMX Agents is established through the interaction component, the user can use the management tool to interact with the MBeans registered in the Agents;
  • Agent layer (Agent layer) : Contains JMX Agents and the MBean Servers they contain. The main component of the Agent layer is the MBean server. As the core of JMX Agents, it acts as the registration center of MBeans. This layer provides 4 Agent services to make MBean management easier: Timer, monitoring, dynamic MBean loading, relationship services;
  • Instruction layer (Instrumentation layer) : Contains MBeans that represent manageable resources. This layer is the closest to managing resources, it consists of MBeans registered in Agents, this MBean allows to manage through JMX Agent. Each MBean exposes operations and accesses to underlying resources;

The specific architecture layering is as follows:

write picture description here

Simple use of JMX

  • Step 1: Create an MBean interface. The name of this interface should end with "MBean", which is to be exposed to the management application, but how it is implemented is not considered by the management application. The MBean interface and The corresponding implementation classes are as follows:

    HelloWorldMBean.java:

    public interface HelloWorldMBean {
        String getGreeting();
        void setGreeting(String greeting);
        void printGreeting();
    }
    • 1
    • 2
    • 3
    • 4
    • 5

    Implement class HelloWorld.java:

    public class HelloWorld implements HelloWorldMBean {
        private String greeting;
    
        public HelloWorld(String greeting) {
            this.greeting = greeting;
        }
        public HelloWorld() {
            this.greeting = "hello world!";
        }
        public String getGreeting() {
            return greeting;
        }
        public void setGreeting(String greeting) {
            this.greeting = greeting;
        }
        public void printGreeting() {
            System.out.println(greeting);
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
  • Step 2: Create MBeanServer and JMX Agent. MBeanServer exists in JMX Agent. The code is as follows:

    public class HelloAgent implements NotificationListener {
        private MBeanServer mbs;
    
        public HelloAgent() {
            this.mbs = MBeanServerFactory.createMBeanServer("HelloAgent");
    
            HelloWorld hw = new HelloWorld();
            ObjectName helloWorldName = null;
            try{
                helloWorldName = new ObjectName("HelloAgent:name=helloWorld");
                mbs.registerMBean(hw, helloWorldName);
            } catch (Exception e) {
                e.printStackTrace();
            }
            startHtmlAdaptorServer();
        }
    
        public void startHtmlAdaptorServer(){
            HtmlAdaptorServer htmlAdaptorServer = new HtmlAdaptorServer();
            ObjectName adapterName = null;
            try {
                // 多个属性使用,分隔
                adapterName = new ObjectName("HelloAgent:name=htmladapter,port=9092");
                htmlAdaptorServer.setPort(9092);
                mbs.registerMBean(htmlAdaptorServer, adapterName);
                htmlAdaptorServer.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void main(String args[]){
            System.out.println(" hello agent is running");
            HelloAgent agent = new HelloAgent();
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • First create the MBean Server and provide a name to uniquely identify the Server, here is the use of factory mode to create the Server
    • Register the MBean we created into the MBean Server, and provide ObjectName for unique identification, which is the unique identification of the domain name + attribute list we mentioned above;
    • Create an Adaptor so that we can test access. Here we use HtmlAdaptorServer, which was provided by sun company before. I always wanted to import it through maven, but I didn't find this package, so I had no choice but to use the HtmlAdaptorServer class, which requires jmxtools.jar, You can go here to download, there are two packages: jmx-1_2_1-ri.zip; jmx_remote-1_0_1_03-ri.zip. After the jmx-1_2_1-ri.zip is decompressed, there are jmxri.jar and jmxtools.jar in the lib. Copy jmxtool.jar and put it in the classpath (jmxri.jar is already included in JDK5+);
    • As can be seen from the above, HtmlAdaptorServer is also an MBean and needs to be added to the MBean Server;

I have always felt that code is the best way to understand concepts and design. Although some official documents and manuals often do not speak human words, the logic in the code can clearly understand the designer's thinking, so after a general understanding of the concept, Going directly to the code is the best!

Copyright statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission. https://blog.csdn.net/lmy86263/article/details/71037316

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324719620&siteId=291194637