Hello Everyone,
In this tutorial, I'm going to show you guys how to create JMX services for your java application.
JMX allows to manage and monitor software applications and also hardware (like printers) through objects called Managed Beans (MBeans for short).
JMX defines a three levels architecture as shown in this diagram :
Probe level defines the MBeans that are going to represent our manageable resources where we implement various services to instrument the target object
for our example, we are going call our Mbean, FirstMbean. FirstMbean is an interface that defines the services that are going to be exposed through the JMX protocol.
public interface FirstMBean {
//Person's name public String getPersonName();
//Person's age public int getPersonAge();
//Person's adress public String getPersonAdress(); public void setPersonAdress(String adress);
}
the implementation of this interface goes like this :
note that the names of the class and interface are important in the JMX ecosystem. a ManagedBean interface should be named like "randomnameMBean " and the implementation goes like " random name".public class First implements FirstMBean {private Person p;public First(){p = new Person();}@Overridepublic String getPersonName() {return p.getName();}@Overridepublic int getPersonAge() {return p.getAge();}@Overridepublic void setPersonAdress(String adress) {p.setAdress(adress);}@Overridepublic String getPersonAdress() {return p.getAdress();}}
here we expose four services three in read-only and one in writing mode. with these services, we can get the name, age, and address of a person, and also we can update the address of that person.
Agent level where the MBeanServer belongs. the MBeanServer act as an interface with the external applications on one side and the MBeans on the other side
we get an instance of the MBeanServer by using the factory ManagementFactory with the method getPlatformMBeanServer().
after that, we register the MBean in the MBeanServer using the method registerMBean of the MBeanServer.
public static void main(String[] args) {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
First bean = new First();
try {
mbs.registerMBean(bean, new ObjectName("com.std.mbean:type=MyMbean"));
} catch (Exception e) {
System.out.println("Error while registring MBean (MyTargetClass) in JMX Agent" + e);
}
// infinit loop to keep the application up and runing
while (true) {
}
}
Remote Management Level contains all external application. that needs the instrumentation of the exposed resources. for this tutorial, we use JConsole for monitoring the Java Application.
with JConsole, we can update variables in order to trigger specific action in the instrumented application.
I hope you guys liked this tutorial,
like, comment and share and if you have any questions, any doubt, let me know in the comment section.