JMX detailed explanation and JConsole use

JMX

JMX (Java Management Extensions) is a framework for implanting management functions in applications. It is a set of standard agents and services. The service is a Java program performance monitoring program officially provided by the JDK. Support remote access, support expansion, that is, custom monitor performance parameters. Provides three levels of calls: network, API, and client. In fact, the Java platform uses JMX as a standard interface for management and monitoring. Any program can obtain all management and monitoring information as long as it accesses this interface according to the JMX specification. Commonly used operation and maintenance monitoring tools such as Zabbix, Nagios and other tools monitor the JVM itself are all information obtained through JMX.

Application scenario

The management page of the middleware software WebLogic is developed based on JMX, while JBoss is the entire system based on the JMX architecture. There are several ways to modify some parameters as follows:

  1. Written dead in the code, modify when you need to change, and then recompile and release.

  2. Written in the configuration file, such as java properties, when you need to change, you only need to modify the configuration file, but the system must be restarted to take effect.

  3. Write a piece of code to cache the configuration value. When the system gets it, first check whether the configuration file has changed. If there is a change, get the latest value from the configuration, otherwise read it from the cache, for example, read the Apollo configuration center data .

  4. Use JMX to concentrate the attributes that need to be configured in a class, then write an MBean, and then perform related configuration, and JMX provides a JConsole tool page to facilitate the modification of parameter values.

JMX architecture

  ┌─────────┐  ┌─────────┐
    │jconsole │  │   Web   │
    └─────────┘  └─────────┘
         │            │
┌ ─ ─ ─ ─│─ ─ ─ ─ ─ ─ ┼ ─ ─ ─ ─
 JVM     ▼            ▼        │
│   ┌─────────┐  ┌─────────┐
  ┌─┤Connector├──┤ Adaptor ├─┐ │
│ │ └─────────┘  └─────────┘ │
  │       MBeanServer        │ │
│ │ ┌──────┐┌──────┐┌──────┐ │
  └─┤MBean1├┤MBean2├┤MBean3├─┘ │
│   └──────┘└──────┘└──────┘
 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘

The structure of JMX is divided into three layers: basic layer (mainly MBean), adaptation layer (Adaptor), interface layer (Connector)

MBean

JMX turns all managed resources into MBeans (ManagedBeans). These MBeans are all managed by MBeanServer. If you want to access MBeans, you can use the external access interface provided by MBeanServer, such as RMI or HTTP.

Using JMX does not need to install any additional components, nor does it require third-party libraries, because MBeanServer is already built into the JavaSErver standard library, and JavaSE also provides a JConsole program for RMI to connect to the MBeanServer, so that the entire process can be managed.

In addition to the JVM will register its various resources as MBeans in JMX, our own configuration and monitoring information can also be registered as MBeans in JMX, so that the management program can directly control the MBeans we expose.

MBeans are divided into the following four types:

Types of description
standard MBean This type of MBean is the simplest. The resources it can manage (including attributes, methods, and time) must be defined in the interface, and then the MBean must implement this interface. Its naming must also follow certain specifications. For example, if our MBean is Hello, the interface must be HelloMBean.
dynamic MBean Must implement javax.management.DynamicMBean interface, all attributes and methods are defined at runtime
open MBean The specification of this MBean is not yet complete and is being improved
model MBean Compared with standard and dynamic MBeans, you don't need to write MBean classes, just use javax.management.modelmbean.RequiredModelMBean. RequiredModelMBean implements the ModelMBean interface, and ModelMBean extends the DynamicMBean interface, so similar to the DynamicMBean, the management resources of the Model MBean are also defined at runtime. Different from DynamicMBean, the resources managed by DynamicMBean are generally defined in DynamicMBean (only those resources are managed at runtime), and the resources managed by model MBean are not in the MBean, but in the external (usually a class), only in the running At the time, it was added to the model MBean through the set method. The following examples will be introduced in detail

Adaptation layer

MBeanServer mainly provides registration and management of resources

Access layer

Provide remote access

Instructions

  1. Write the management interface and monitoring data provided by the MBean.
  2. Register MBean

Case:

Add the annotation @EnableMBeanExport to the startup program to tell spring to automatically register the MBean

@SpringBootApplication
@MapperScan(basePackages = "com.lyj.demo.mapper")
@EnableMBeanExport // 自动注册MBean
public class SpringbootDemoApplication {
    
    

    private static final Logger logger = LoggerFactory.getLogger(SpringbootDemoApplication.class);
    public static void main(String[] args) {
    
    
        SpringApplication.run(SpringbootDemoApplication.class, args);
        }
        }

Write MBean, here is to configure blacklist data as an example, through JConsole to obtain configuration data and add data to delete data, and the configuration will take effect immediately without recompiling and publishing code.

package com.lyj.demo.mbean;

import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedOperationParameter;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author 凌兮
 * @date 2021/3/25 14:05
 * 黑名单MBean类名必须以MBean结尾,这是规则
 */
@Component
// 表示这是一个MBean,将要被注册到JMX,objectName指定了这个MBean的名字,通常以company:name=Xxx(公司名);来分类MBean
@ManagedResource(objectName = "company:name = blackList", description = "blackList of Ip address")
public class BlackListMBean {
    
    
    private static Set<String> ips = new HashSet<>();

    static {
    
    
        ips.add("123");
        ips.add("234");
    }

    /**
     * 对于属性,使用@ManagedAttribute注解标注,本次的MBean只有get属性,没有set
     * 属性,说明这是一个只读属性。
     * @return
     */
    @ManagedAttribute(description = "Get IP addresses in blacklist")
    public String[] getBlacklist() {
    
    
        return ips.toArray(new String[1]);
    }

    /**
     * 对于操作,使用@ManagedOperation注解标注,操作有addBlacklist()和
     * removeBlacklist()其他方法如shouldBlock()不会被暴露给JMX。
     * @param ip
     */
    @ManagedOperation
    @ManagedOperationParameter(name = "ip", description = "Target IP address that will be added to blacklist")
    public void addBlacklist(String ip) {
    
    
        ips.add(ip);
    }

    @ManagedOperation
    @ManagedOperationParameter(name = "ip", description = "Target IP address that will be removed from blacklist")
    public void removeBlacklist(String ip) {
    
    
        ips.remove(ip);
    }

    public boolean shouldBlock(String ip) {
    
    
        return ips.contains(ip);
    }
}

Intercept interface and implementation class:

public interface IpInterceptor {
    
    

    boolean preHandle(String ip);
}
@Component
@Slf4j
public class BlackIpHandle implements IpInterceptor {
    
    
    @Autowired
    private BlackListMBean blackListMBean;

    @Override
    public boolean preHandle(String ip) {
    
    
        return blackListMBean.shouldBlock(ip);
    }
}

testing method:

@RequestMapping("/test/Jmx/{str}")
public void jmxTest(@PathVariable(value = "str") String str) {
    
    
    if (blackIpHandle.preHandle(str)) {
    
    
        loggger.warn("拦截成功");
        return;
    }
    loggger.warn("拦截失败");
    return;
}

Start the application, open JConsole.exe in the bin file in the jdk file in java, find your application, and connect to it
Insert picture description here
. You can view the memory and stack thread information in JConsole. You can see the MBean list here. Find our registered Mean (company)
, which contains attributes, operations, notifications, etc.
First, we execute the result of the method of obtaining blacklist data: Insert picture description here
you can see three data, and the same is true for adding data. 6666 was later dynamically added by JConsole , And then execute the request and directly intercept it successfully. Here we directly test the results as shown in the figure:
Insert picture description here

Java program opens JMX service

If you want to monitor a Java program, you need to add JMX related parameters when the program starts (local connection, you can add or not here, the port number here is the port number that JConsole listens to, not the port number of the service).

-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9102
-Dcom.sun.management.jmxremote.authenticate=false 
-Dcom.sun.management.jmxremote.ssl=false

The three parameters are: service port, security policy, SSL encryption

Remote Connection

The test environment is deployed on the RedHat6.5 server. Generally, the following parameters can be added to allow remote connections.

-Dcom.sun.management.jmxremote.port=8999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

However, the actual test cannot be connected. After querying the information, the final configuration is as follows, and the remote connection is realized.

(java -jar -Dcom.sun.management.jmxremote  -Dcom.sun.management.jmxremote.port=8999 -Dcom.sun.management.jmxremote.rmi.port=9999 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false app-1.0.jar&)

At the same time, you need to pay attention to whether the port of the server is blocked, and whether the hosts are configured with the actual IP. You can use the hostname -i command to query whether the ip is valid. For example, the actual ip is 10.10.10.101 and the computer name is mycomputer. The hosts configuration is as follows:

10.10.10.101   mycomputer

Guess you like

Origin blog.csdn.net/qq_40093255/article/details/115208924