Build a JMX-based management system for your Web application

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

Author: Sheng

The Web application system was developed, and then how to make it easy for customers (Web application administrators) to manage a bunch of my configuration files, or how to dynamically modify the system run properties, while allowing customers to implement these management without having to be too knowledgeable about the contents of the configuration file. This is a problem that many of the system analysts who have just ended the development of Web application systems need to face. Or I would like to have already completed the Web application System for effective resource management, and hope to add management functions, the original code does not need to do too much modification, in other words, management system and managed application system to do a good job of isolation. The JMX management framework (Figure 1) gives you a good solution to these problems.

JMX (Java Management Extensions) is a resource for managing networks, devices, applications, and so on, which describes a scalable management architecture and provides the JMX API and some Java management services to be defined. At the time of this 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 JMX was launched, a JMX-based implementation framework, such as Jakarta Tomcat and JBoss, was immediately adopted by some large projects, which illustrates the feasibility and good characteristics of JMX from a sub-point.

The management of the Web application 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, the dynamic change log level will be more cumbersome, and may be the structure of the system messy, resulting in poor structural consequences, Not to mention extensibility. The hierarchical structure of JMX, as well as its high level of component-making, enables us to implement a highly scalable management solution for existing Web applications by encapsulating various resources into Mbean.

This article takes tomcat as a Web server as an example, and describes in detail how to use JMX to establish the management of Web applications. For the concept of JMX, architecture and the use of the specification has a lot of relevant documents, in order to be able to better understand this article, please refer to these documents when reading this article, the text will focus on the application and implementation. The following figure (Figure 2) is a basic framework diagram of JMX (see JMX specification), which is intended to give you an understanding of the convenience of this article.

I. Create a management system for Web applications

What are the things we need to do to build a JMX-based management system for Web applications? Create an instance of Mbean for each resource that needs to be managed, as required by the JMX framework, with two types of instances to choose from, an mbean that manages resources directly, and an mbean that is managed by invoking a resource instance. Writing an Mbean profile and describing each mbean, choosing an Mbean profile based on XML is a good decision. Generate an Mbean by reading the Mbean profile and generating the mbeaninfo. Register the Mbean that needs to be managed with the Mbean server. It is also easier to write client-side code and choose the Web to make the client's encoding compare to the style of the Web application.

Then a JMX-based Web application Management framework has been formed, figure 3 is its basic structure diagram, the dashed part of the 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 the Mbeanserver instance of the Web server, the advantage is that through the mbeanserver to itself, you can even implement some management of the Web server itself. Tomcat's management framework is also built on JMX, and it uses the JMX implementation to be mx4j, which is a very good JMX open source project, in tomcat4.1.27, where mbeanserver instances are stored with properties named " Org.apache.catalina.MBeanServer "Application variable (several ranges of variables in Web applications: page,request,session,application), So the way to get mbeanserver instances in the servlet:

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

If this is the case, the server you get is null, which means you must also complete the following work so that you can have access to the system's Mbeanserver,tomcat before the Mbeanserver instance is placed under the Web Application property name " Org.apache.catalina.MBeanServer "in the system variable.

Locate the Tomcat under Conf directory and modify the Server.xml file. Modify the Web app's context element to add the privileged= "true" property, for example:

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

2. Create an instance of Mbeanserver through the Creatembeanserver () method of the Mbeanserverfactory class in the JMX API, which makes the JMX implementation independent of the Web server and makes the code more portable. After Mbeanserver is created, it can be placed into the application variable (recommended), or created and obtained using singleton design pattern, in order to make it easy to get a reference to the Mbeanserver in the management system.

The code for creating 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 obtain mbeanserver, so we can consider the convenience of implementation.

Iii. Creating an Mbean

In order to be able to manage the resources of Web applications, first of all to enable the resources to be managed, according to the JMX specification, we encapsulate the resources into Mbean, in fact, to add manageability to the Web application.

After obtaining an instance of Mbeanserver, you can write your own mbean, according to the specification of JMX, Mbean has standard and dynamic two main types, here do not repeat, specifically, you can see the specification of JMX (http://). There are two types of dynamic MBeans for special purposes: Model Mbean and open Mbean. Model Mbean (Modle Mbean) provides an "off-the-shelf" Mbean implementation that you can use to quickly leverage any JMX manageable resource. It is a pre-fabricated, 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 to be customized at run time. This enables Java-based, non-instrumental resources to provide a guaranteed, compliant MBean virtual package at run time, enabling them to be managed through the JMX architecture. In the Web application, resources are diversified, there are running instances, static files, or even equipment or hardware status, then we can divide these resources into two categories, some resources need dynamic management monitoring (such as number of users, database connection monitoring, instant logs, 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 the Mbean to directly invoke the interfaces provided by the running instance, on the other hand, and hope that the Mbean itself can provide the management of the static resources. Model Mbean is a great way to meet this requirement and provides flexibility and scalability for new resources that need to be managed, so the model Mbean is recommended as a Web application preference. Of course, the specific type of mbean that needs to be used in combination with different applications, or multiple types of mbean. Incidentally, the use of 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 also 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 implement modifications to the database configuration file, so that when the Web application restarts, the new database configuration is used, and we implement the direct operation of the resource using the Mbean's provision. The purpose of a dynamically managed Mbean 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 App.

1. Implement the Mbean for managing configuration files.

The

Jdbcconfig is a model MBean, Its role is to encapsulate the config.properties file into an Mbean, which consists of four attributes and their associated getter and setter and a Save method, where the function of the Save method is to store the property in the configuration file, thereby allowing the configuration file to be manipulated directly through the 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 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 ();            } 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!";            } catch (Exception e) {try {if (out! = null) out.close ();            } catch (IOException E1) {e1.printstacktrace ();            } e.printstacktrace ();        Return "Save error!"; }    }}

2. Implement modifying the properties of the running instance.

The example above is a modification to a static resource, and the Model Mbean also provides a good way to modify a running instance of a class if it needs to be dynamically modified. There is a setmanagedresourced method in the Javax.management.ModelMBean API that does this by placing a running class instance into the model MBean, which is actually all there is to do. When it is necessary to change the attribute of an instance, it is only necessary to invoke the SetAttribute method of the Mbean, and the Mbean will invoke the property setting method corresponding to that instance by reflection, which is simple. But many people like to understand the process directly from the code, so I'll write about how to implement the property Code of the dynamic modification instance. Also in the case of JDBC, assuming that the system already has a database connection using JDBC, it is time to change the JDBC properties and establish a new connection, all without restarting the Web application.

The first code is the database connection class used by the Web app, which provides a database connection, two methods for testing the connection properties, and related properties. When the web app starts, the class will be instantiated, and we'll 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 code is a model Mbean class, which, like the first model Mbean mentioned earlier, inherits Basemodelmbean, but it will have a reference to the Web Application Runtime resource instance, because all the properties and methods are in the referenced resource instance. The parent class Basemodelmbean completes the property setting method that calls the resource instance through reflection, so the class is very simple to write, and we can do some other related methods in it.

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 application Run initial database connection created **/dbaccess DBAccess = new DBAccess ();d baccess.setdriver ();d Baccess.setpassword (); Dbaccess.setusername ();d baccess.setdburl ();/** Create and register the mbean//creation of the management database Mbeanresinstancembean mbean= new Resinstancembean ()///Set Mbeaninfo, which is required Mbean.setmodelmbeaninfo (Creatembeaninfo ());//Set the resource instance managed by the Mbean, Instance is a database connection instance,//"objectreference" is required, otherwise you will not be able to set the resource instance into the Mbean, remember the line dbaccess instance = getdbaccess (); Mbean.setmanagedresource (instance, "Objectreference");//register Mbean to Mbean server Mbeanserver serv = getmbeanserver (); O Bjectname oname = Createobjectname (Mbean); Serv.registermbean (Mbean, oname);

Iv. Creating an Mbean profile

In the third code above, we can see that to register an Mbean with an Mbean server you must first create the Mbeaninfo,mbean setmodelmbeaninfo () to set the Mbeaninfo to the Mbean. In order to be able to obtain the information of Mbean flexibly and thus register the Mbean to Mbeanserver, it is mentioned in the "Best Practices of Java Enterprise" published by O ' Reilly that it is a very good choice to use XML file to describe Mbean. and provides an example of an XML description, so this article also recommends ways to use Mbean profiles in managing Web applications. In fact no matter tomcat4. X, or JBoss, the Mbean is created using the Mbean profile, which provides an Mbean description file scheme in the tomcat4.x that describes the two database connection management Mbean mentioned above. Tomcat provides a way to read the description file, which can be viewed in 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 password "type=" java.lang.String "/> <operation 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, it is necessary to obtain the description of the Mbean and save it in an instance of Mbeaninfo, otherwise it is not possible to register the Mbean with the Mbean server, through the Mbean profile, Getting the description of the various types of Mbean is a very simple thing, which is what is needed to create an mbean, the advantage is that you do not need to write code, only need to modify the description file, you can add a new Mbean, the registered code is actually our previous code is listed. An Mbean must be registered with the corresponding Objectname,objectname equivalent to the Mbean's unique name in the Mbean server, in the form of "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 the server-side Mbean, and the next step is how to enable users to manage resources using these mbean. Although the htmladapter is provided in the reference implementation of JMX, it allows the user to use the Mbean through the browser. But the interface is not so friendly and amiable, and the customers who have always been harsh will never be satisfied. Therefore, it is still necessary to write some concise access to the Mbean page. How to access the Mbean through Java, you can refer to JMX's data, which is very much.

According to the above, JMX-based management framework is a very sensible choice if you want to add management or management systems to Web applications.

In the next Caishuxueqian, inevitably errors and omissions, but also look at people, generous enlighten in the next, in the next grateful to the heart.

about the author

Sheng, a senior programmer in Shanghai branch of Guangzhou Extension Micro Technology Co., Ltd., is obsessed with various Java technologies, participates in many large Java projects, and designs and implements 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.