Building a JMX based management system for your Web application

Source: Internet
Author: User
Tags documentation reflection access database jboss tomcat

Author: Sheng

The Web application system has finally developed, how to let customers (Web Application system administrators) easily manage my pile of configuration files, or how to dynamically modify the system run properties, but also so that customers do not need too much understanding of the contents of the configuration file can achieve these management. This is the problem that many system analysts who have just completed the early development of Web application systems need to face. Or that I want to have already completed the Web application System for effective resource management, I hope to add management functions at the same time, the original code does not need to do too much modification, in other words, management system and the management of the application system to do a good job of isolation. The JMX management framework (Figure 1) solves these problems well for you.

JMX (Java Management Extensions) manages resources such as networks, devices, applications, and describes an extensible management architecture that provides a JMX API and some Java management services to define. At the time of writing, the latest version of the JMX specification is v1.2 (http://jcp.org/aboutJava/communityprocess/final/jsr003/index3.html), and the latest version of the JMX reference implementation is v1.2.1 ( http://java.sun.com/products/JavaManagement/). After the JMX launch, some large projects immediately adopted a JMX based implementation framework, such as Jakarta Tomcat and JBoss, which illustrates the feasibility and good nature of JMX.

For Web application management is often troublesome, such as the customer manually modify the configuration file, open the database monitoring program, and so on, if you want to dynamically modify the database access scheme or monitor the number of users, dynamic change log level will be more cumbersome, and may be the structure of the system messy, resulting in poor structure, Not to mention extensibility. JMX's layered architecture and high level of component enable us to implement a highly scalable management solution for existing Web applications at low cost by encapsulating various resources in an Mbean format.

This article takes tomcat as a Web server as an example, detailing how to use JMX to build management of Web applications. For the concept of JMX, architecture and the use of specifications have a lot of relevant documentation, in order to be able to better understand this article, read this article, please refer to these documents, the text will focus on the application and implementation. The following figure (Figure 2) is the basic framework for JMX (see JMX specification), and is designed to give you an idea of the convenience of this article.

I. Creating a management system for Web applications

To build a JMX based management system for Web applications, what do we need to do about it? Create an Mbean instance for each resource that needs to be managed, as required by the JMX framework, with two types of instances to choose from, one for managing resources directly, and one for managing an mbean by invoking a resource instance. It is a good decision to write an Mbean description file and describe each Mbean, and choose an xml-based mbean description file. An mbean is generated by reading the Mbean description file, generating mbeaninfo. Register the Mbean that needs to be managed into the Mbean server. Writing client-side code, choosing the way of the web to do the client's coding compared to the style of Web application is also easier to implement.

Then a JMX based Web application Management framework has been formed, figure 3 is its basic structure diagram, the dotted line is a JMX based management system. Next we follow the steps to implement the entire management system.

Ii. Examples of obtaining mbeanserver

There are two scenarios for obtaining an instance of Mbeanserver.

1, by getting a mbeanserver instance of the Web server, the benefit is that through the mbeanserver to itself, even some of the Web server itself can be managed. Tomcat's management framework is also built on JMX based, it uses the JMX implementation is mx4j, this is a very good JMX open source project, in tomcat4.1.27, mbeanserver instance is stored with the property named " Org.apache.catalina.MBeanServer "Application variable (several ranges of variables in Web applications: page,request,session,application), So the way to get the Mbeanserver instance in the servlet:

Server = (mbeanserver)    getservletcontext (). getattribute ("Org.apache.catalina.MBeanServer");

If you get a null server in this way, it means you have to do the following work so that you have access to the mbeanserver,tomcat of the system to keep the Mbeanserver instance under the Web Application property name " Org.apache.catalina.MBeanServer "in the system variable.

Locate Tomcat under the Conf directory and modify the Server.xml file. Modify the context element of the Web application to add a property such as privileged= "true", for example:

<context path= "/myapp" docbase= "c:/web/" debug= "9"     privileged= "true" reloadable= "true" crosscontext= "true"/ >

2. Create Mbeanserver instances through the Creatembeanserver () method of the Mbeanserverfactory class in the JMX API, which makes the implementation of JMX irrelevant to the Web server and makes the code more portable. After Mbeanserver is created, you can place it in a application variable (recommended), or create and obtain it using the singleton design pattern, in order to make it easy to obtain a reference to the Mbeanserver in the management system.

The code to create an Mbean server using the JMX API is as follows:

Mbeanserver Server = Mbeanserverfactory.creatembeanserver ();

It is not very important to decide what kind of scheme to get mbeanserver, and it is possible to consider the convenience of implementation.

third, create an Mbean

In order to manage the resources of Web applications, first of all, to enable resources to be managed, as required by the JMX specification, we encapsulate resources into Mbean, which in effect adds manageability to Web applications.

Once you've got an instance of Mbeanserver, you can write your own mbean, which, according to the JMX specification, has both standard and dynamic two main types, not to be discussed here, specifically, the JMX specification (http://). There are two types of dynamic Mbeans for special purposes: Model Mbean and open Mbean. Model Mbean (Modle mbean) provides a "ready-made" Mbean implementation that you can use to quickly leverage any JMX-manageable resources. It is a prefabricated, generic, and dynamic MBean class, and provides a reference implementation that already contains all the necessary default behavior implementations-allowing you to add or overwrite those implementations that need customization at run time. This enables java-based, non-toolset resources to provide guaranteed, compliant MBean virtual packages at runtime, enabling them to be managed through the JMX architecture. In Web applications, resources are diversified, there are running instances, static files, or even equipment or hardware status, then we put these resources can be divided into two categories, some resources need to carry out dynamic management monitoring (such as the number of landing users, database connection monitoring, real-time log, etc.), some are static resources, Only static management (System configuration file, log level, etc.) is required to manage these different types of resources, which requires mbean to directly invoke the interface provided by the running instance and, on the other hand, the Mbean itself to provide the management of static resources, Model Mbean satisfies this requirement and provides great flexibility and scalability for new resources that need to be managed, so the recommended model Mbean is preferred as a Web application. Of course, the specific type of mbean needs to be combined with different applications or multiple types of mbean. By the way, using different types of mbean is transparent to the management client, which means that the client uses a consistent access method to access the properties and methods of the Mbean, which is an advantage of JMX.

In order to better observe how to realize the management of static resources and dynamic resources, this paper has written two Mbean, which realizes the static and dynamic management of the database connection properties respectively. The purpose of a statically managed Mbean is to modify the database configuration file so that when the Web application is restarted, the new database configuration is used, and we implement the direct operation of the resource with the Mbean. The Mbean purpose of dynamic management is to modify the properties of a database connection object that has already been instantiated, so that the database connection is changed without restarting the Web application.

1, the implementation of the administrative configuration file Mbean.

Jdbcconfig is a model MBean, Its role is to encapsulate the Config.properties file as an Mbean, which includes four properties and their associated getter and setter and a Save method, where the Save method functions as a property in a configuration file, enabling the configuration file to be manipulated directly through an mbean. The Mbean in this example inherits the Basemodelmbean class, This class implements the Javax.management.ModelMBean interface, we can find the Basemodelmbean class in Commons-modeler.jar, Commons-modeler.jar is an open source package used in the tomcat4.x.

Import Javax.management.mbeanexception;import Javax.management.runtimeoperationsexception;import Org.apache.commons.modeler.basemodelmbean;import Java.io.*;import Java.util.properties;public Class    Jdbcconfigmbean extends Basemodelmbean {private String driver;    Private String username;    private String password;    Private String Dburl;    private static final String Config_filepath = "C://myweb//conf//config.properties"; Constructor///////////////////////////////         Public Jdbcconfig () throws Mbeanexception, Runtimeoperationsexception {        Super ();    Init ();        private void Init () {inputstream in = null;            try {Properties prop = new properties ();            in = new Bufferedinputstream (new FileInputStream (Config_filepath));            Prop.load (in);        Driver = Prop.getproperty ("Driver");    Dburl = Prop.getproperty ("Dburl");            Username = Prop.getproperty ("username");            Password = prop.getproperty ("password");        In.close ();            The catch (Exception e) {try {if (in!= null) in.close ();            catch (IOException E1) {e1.printstacktrace ();        } e.printstacktrace (); }}/////////////////////////////////////////////////////////////////////getter and setter////////////////////// /////////////////////////////////////////////    //////////////////////////////////////////////////////////////////        ///public Method///////////////////////////////////////////////////////////////////public String Save () {        OutputStream out = null;            try {out = new Bufferedoutputstream (new FileOutputStream (Config_filepath));            Properties prop = new properties ();            Prop.setproperty ("Driver", driver); ProP.setproperty ("Dburl", Dburl);            Prop.setproperty ("username", username);            Prop.setproperty ("password", password);            Prop.store (out, "---jdbc config---");            Out.close ();        Return "Save Success!";            The catch (Exception e) {try {if (out!= null) out.close ();            catch (IOException E1) {e1.printstacktrace ();            } e.printstacktrace ();        Return "Save error!"; }    }}

2, the implementation of the modified run instance properties.

The example above is a modification to a static resource, and if you need to dynamically modify a running class instance, the Model Mbean also provides a good way to There is a setmanagedresourced method in the Javax.management.ModelMBean API that is used to put a running class instance into the model MBean, and so much more is actually done. When it is necessary to change the instance properties, it is simple to invoke the SetAttribute method of the Mbean, which will invoke the corresponding property setting method of the instance through reflection. But many people prefer to understand the process directly from the code, so I'll write out how to implement the property code that dynamically modifies the instance. Also, take JDBC as an example, assuming that the system already has a database connection using JDBC, now you need to change the properties of JDBC and establish a new connection, all without restarting the Web application system.

The first piece of code is the database connection class used by Web applications, which provides a two method for obtaining a database connection and testing the properties of a connection, as well as related properties. When the Web application is started, the class is instantiated, and we call this instance a resource instance.

Package Com.myapp.db;import Java.sql.connection;import Java.sql.sqlexception;public class DBAccess {    private String driver;    Private String username;    private String password;    Private String Dburl;    Public Connection getconnection ()    {	...           }    public static Boolean testconnection (String driver,string username,	    string password,string dburl)    {    }    ///////////////////////////////////////////////////////////////////    //getter and setter    //////// ///////////////////////////////////////////////////////////}

The second piece of code is a model Mbean class that inherits Basemodelmbean like the first model Mbean mentioned earlier, but it will have a reference to a resource instance of the Web application runtime, because all properties and methods are in the referenced resource instance. The parent class Basemodelmbean completes the property setting method that invokes the resource instance through reflection, so the writing of this class is fairly simple, and we can do some other related methods inside.

Package Com.myapp.db;import Org.apache.commons.modeler.basemodelmbean;import javax.management.MBeanException; Import Javax.management.runtimeoperationsexception;public class Resinstancembean extends Basemodelmbean {public    Resinstancembean ()            throws Mbeanexception, runtimeoperationsexception {        super ();    }    /** Other operations **/...    }

The third piece of code is how to implement a running instance of the management database connection class.

/**web The database connection created at the beginning of the application run **/dbaccess DBAccess = new DBAccess ();d baccess.setdriver ();d Baccess.setpassword (); Dbaccess.setusername ();d baccess.setdburl ();/** Create and register the mbean//of the admin database Mbeanresinstancembean mbean= New Resinstancembean ()//Set Mbeaninfo, which is required Mbean.setmodelmbeaninfo (Creatembeaninfo ());//Set the resource instance managed by the Mbean, instance for the database connection instance,//"objectreference" is required, otherwise you will not be able to set the resource instance to the Mbean, remember on the line dbaccess instance = getdbaccess (); Mbean.setmanagedresource (instance, "Objectreference")//registered Mbean to Mbean server Mbeanserver serv = getmbeanserver (); O Bjectname oname = Createobjectname (Mbean); Serv.registermbean (Mbean, oname);

Iv. Creating an mbean description file

In the third paragraph of code above, we can see that to register an Mbean in the Mbean server you must first create a Mbeaninfo,mbean setmodelmbeaninfo () to set the Mbeaninfo to the Mbean. In order to be able to obtain information about the Mbean flexibly, thereby registering the Mbean with Mbeanserver, in O ' Reilly's published "Best Practice for Java Enterprise", it is a good choice to use an XML file to describe an Mbean description. and provides an example of an XML description, so this article also recommends using an Mbean profile for managing Web applications. In fact, no matter tomcat4. X, or JBoss, uses an Mbean description file to create an Mbean, which provides an Mbean description file scheme within the tomcat4.x, and describes the two Mbean of database connection management mentioned above. Tomcat provides a way to read the profile, and see the help documentation provided by Tomcat-how to use the Mbean descriptor ("http://jakarta.apache.org/tomcat/tomcat-4.1-doc/ Mbeans-descriptor-howto.html ").

<mbean-list><mbean name= "Jdbcconfigmbean" Classname= "Com.myApp.jmx.JDBCConfigMBean" D Escription= "The object to Access database" domain= "MyApp" > <attribute name= "Driver" desc    ription= "JDBC driver name" type= "Java.lang.String" writeable= "false"/> <attribute Name= "Dburl" description= "Database url" type= "java.lang.String"/> <attribute "name=" Username "description=" Database user name "type=" java.lang.String/> <attribute name=   Password "description=" vthe user name ' s password ' type= ' java.lang.String '/> Name= "Save" description= "Save the Configuration" impact= "ACTION" returntype= "Java.lang.s Tring "> </operation> </mbean><mbean name=" DBAccess "Classname=" Com.myApp.jmx.ResI Nstancembean "DEscription= "The object to Access database" domain= "MyApp" type= "com.myApp.db.DBAccess" >                 <attribute name= "Driver" description= "JDBC driver name" type= "Java.lang.String" Writeable= "false"/> <attribute name= "Dburl" description= "Database url" type= "Jav A.lang.string "/> <attribute name=" username "description=" Database user name "Type=" JAV A.lang.string "/> <attribute name=" password "description=" vthe user name ' s password ' ty               Pe= "java.lang.String"/> <operation name= "testconnection" description= "Test Configure attribute" impact= "ACTION" returntype= "java.lang.String" > <parameter name= "Driver" Descriptio n= "JDBC driver name for test" type= "java.lang.String"/> <parameter name= "username" D escription= "Database useR name for test "type=" java.lang.String "/> <parameter name=" password "description=" t          He user name ' s password for test ' type= ' java.lang.String '/> <parameter name= ' Dburl ' description= "Database URL for test" type= "java.lang.String"/> </operation> </mbean&gt ;</mbean-list>

v. Registration of Mbean

Before registering an mbean, you must get descriptive information about the Mbean and save it in the Mbeaninfo instance, otherwise you cannot register the Mbean in the Mbean server, through the Mbean description file, Getting descriptive information about the various types of Mbean is a very simple thing, and that's what it takes to create an mbean, and the advantage is that you can add a new mbean without having to write code, just modify the description file, and the code in question is actually listed in our previous code. When an Mbean is registered, the corresponding objectname,objectname must be specified equivalent to the unique name of the Mbean in the Mbean server, which is in the format: "Domain:key1=value1,key2=value2 ...", A set of named rules can be defined according to the requirements of the system.

Register Mbean to Mbean server Mbeanserver serv = getmbeanserver (); objectname oname = Createobjectname (Mbean); Serv.registermbean (Mbean, oname);

Vi. Client Writing the management framework

We have completed the registration of server-side Mbean, and then how to enable users to manage resources using these mbean. Although the htmladapter is provided in the JMX reference implementation, the user is able to use the Mbean through the browser. However, the interface provided is not so friendly, and always demanding customers will not be satisfied with this. Therefore, it is necessary to write some concise access to the Mbean page. How to access an Mbean through Java, you can see the JMX data, which is very much.

According to the above, a JMX-based management framework is definitely a smart choice if you want to increase the management or management of Web applications.

In the next talents, inevitable mistakes, but also hope Insight, generous enlighten in the next, in the next gratitude to the heart.

about the author

Sheng, Guangzhou tuo Micro Technology Co., Ltd. Shanghai branch of senior programmers, a variety of Java technology is very obsessed, participate in a number of large Java projects, and design the implementation of its management system.

trackback:http://tb.blog.csdn.net/trackback.aspx?postid=1826544

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.