博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Manage, Administrate and Monitor GlassFish v3 from Java code usingAMX & JMX
阅读量:5354 次
发布时间:2019-06-15

本文共 15649 字,大约阅读时间需要 52 分钟。

Manage, Administrate and Monitor GlassFish v3 from Java code usingAMX & JMX

0

Management is one of the most crucialparts of an application server set of functionalities. Developmentof the application which we deploy into the server happens oncewith minor development iteration during the software lifecycle, butthe management is a lifetime task. One of the very powerfulfeatures of the GlassFish application server is the powerfuladministration and management channels that it provides fordifferent level of administrators and developers whom want toextend the application server administration and managementinterfaces.

GlassFish as an application servercapable or serving mission critical and large scale applicationsbenefits from several administration channel including the CLI, webbased administration console and finally the possibility to managethe application server by using standard Java management extensionor the JMX.

Not only GlassFish fully expose itsmanagement functionalities as JMX MBeans but also it provides avery easier way to manage the application server using localobjects which proxies JMX MBeans. These local objects are providedas AMX APIs which lift the need for learning JMX by administers anddevelopers whom want to interact with the application server bycode.

GlassFish provides very powerfulmonitoring APIs in term of AMX MBeans which let developers andadministrators monitor any aspect of anything inside theapplication server using Java code without need to understand theJMX APIs or complexity of monitoring factors and statisticsgathering. These monitoring APIs allows developers to monitor abulk of Java EE functionalities together or just monitor or singleattribute of a single configuration piece.

GlassFish self management capability isanother powerful feature based on the AMX and JMX APIs to letadministrators easily automate daily tasks which can consume ahandful amount of time without automation. Self management canmanage the application server dynamically by monitoring theapplication server in runtime and changing the application serverconfiguration dynamically based on predefined rules.

1 Java Management eXtension (JMX)

JMX, native to Java platform,introduced to let Java developers have a standard and easy to learnand use way for managing and monitoring their Java applications andJava enabled devices. We as architects, designers and developers ofJava applications which can be as small as an in house invoicemanagement or as big as a running stock exchange system need a wayto expose management of our developed software to other industryaccepted management software and JMX is the answer to theseneed.

1.1 What is JMX?

JMX is a part of Java Standard editionand was present from early days of Java platform existence and seenmany enhancements during Java platform evolution. The JMX relatedspecifications define the architecture, design patterns, APIs, andservices in the Java programming language for managing andmonitoring applications and Java enabled devices.

Using the JMX technology, we candevelop Java classes which perform the management and monitoringtasks and expose a set of their functionalities or attributes bymeans of an interface to which later on are exposed to JMX clientsthrough specific JMX services. The objects which we use to performand expose management functionalities are called Managed Beans orMBeans in brief.

In order for MBeans to be accessible toJMX clients, which will use them to perform management tasks orgathers monitoring data, they need to be registered in a registrywhich later on let our JMX client application to find andinitialize them. This registry is one of the fundamental JMXservices and called MBean Server.

Now that we have our MBeans registeredwith a registry, we should have a way to let clients communicatewith the running application which registered the MBeans to executeour MBeans operations, this part of the system is called JMXconnectors which let us communicate with the agent from a remote orlocal management station. The JMX connector and adapter APIprovides a two way converter which can transparently connect to JMXagent over different protocols and provides a standard way formanagement software to communicate with the JMX agents regardlessof communication protocol.

1.2 JMX architecture

The JMX benefits from a layeredarchitecture heavily based on the interfaces to provideindependency between different layers in term of how each layerworks and how the data and services are provided for each layer byits previous one.

We can divide the JMX architecture tothree layers. Each layer only relay on its direct bottom layer andis not aware of its upper layer functionalities. These layers are:instrumentation, agent, and management layers. Each layer providessome services either for other layers, in-JVM clients or remoteclients running in other JVMs. Figure 1 shows different layers ofJMX architecture.

Figure 1 JMX layerd architecture andeach layer components

Instrumentation layer

This layer contains MBeans and theresources that MBeans are intended to manage. Any resource that hasa Java object representative can be instrumented by MBeans. MBeanscan change the value of object’s attributes or call itsoperations which can affect the resource that this particular Javaobject represents. In addition to MBeans, notification model andMBean metadata objects are categorized in this layer. There are twodifferent types of MBeans for different use cases, these typesinclude:

Standard MBeans: Standard MBeansconsisting of an MBean interface which define the exposedoperations and properties (using getters and setters) and the MBeanimplementation class. The MBean implementation class and theinterface naming should follow a standard naming pattern inStandard MBeans. There is another type of standard MBeans whichlift the urge for following the naming pattern called MXBeans. TheStandard MBeans naming pattern for MBeans interface isClassNameMBean and the implementation class is ClassName. For theMXBeans naming pattern for the interface is AnythingMXBean and theimplementation class can have any name. We will discuss this namingmatter in more details later on.

Dynamic MBeans: A dynamic MBeanimplements javax.management.DynamicMBean, instead of implementingan static interface with a set of predefined methods. DynamicMBeans relies on javax.management.MBeanInfo that represents theattributes and operations exposed by them. MBeans clientapplication call generic getters and setters whose implementationmust resolve the attribute or operation name to its intendedbehavior. Faster implementation of JMX management MBeans for analready completed application and the amount of informationprovided by MBeans metadata classes are two benefits of DynamicMBeans.

Notification Model: JMX technologyintroduces a notification model based on the Java event model.Using this event model MBeans can emit notifications and anyinterested party can receive and process them, interested partiescan be management applications or other MBeans.

MBean Metadata Classes: These classescontain the structures to describe all components of an MBean’smanagement interface including its attributes, operations,notification, and constructors. For each of these, the MBeanInfoclass include a name, a description and its particularcharacteristics (for example, an attribute is readable, writeable,or both; for an operation, the signature of its parameter andreturn types).

Agent layer

This layer contains the JMX Agentswhich are intended to expose the MBeans to management applications.The JMX agent’s implementation specifications fall under thislayer. Agents are usually located in the same JVM that MBeans arelocated but it is not an obligation. The JMX agent consisting of anMBean server and some helper services which facilitate MBeansoperations. Management software access the agent trough an adapteror connecter based on the management application communicationprotocol.

MBean Server: This is the MBeansregistry, where management applications will look to find whichMBeans are available to them to use. The registry expose the MBeansmanagement interface and not the implementation class. The MBeansregistry provides two interfaces for accessing the MBeans from aremote and in the same JVM client. MBeans can be registered byanother MBeans, by the management application or by the Agentitself. MBeans are distinguished by a unique name which we willdiscuss more in AMX section.

Agent Services: there some helperservices for MBeans and agent to facilitate some functionalities.These services include: Timer, dynamic class loader, observers toobserver numeric or string based properties of MBeans, and finallyrelation service which define associations between MBeans andenforces the cardinality of the relation based on predefinedrelation types.

Management layer

The Management tier contains componentsrequired for developing management applications capable ofcommunicating with JMX agents. Such components provide an interfacefor a management application to interact with JMX agents through aconnector. This layer may contain multiple adapters and connectorsto expose the JMX agent and its attached MBeans to differentmanagement platforms like SNMP or exposing them in a semantic richformat like HTML.

JMX related JSRs

There are six different JSRs definedfor the JMX related specifications during past 10 years. These JSRsinclude:

JMX 1.2 (JSR 3): First version of JMXwhich was included in J2SE 1.2

J2EE Management (JSR 77): A set ofstandard MBeans to expose application servers’ resources likeapplications, domains, and so on for management purposes.

JMX Remote API 1.0 (JSR 160):interaction with the JMX agents using RMI from a removelocaten.

Monitoring and Management Specificationfor the JVM (JSR 174): a set of API and standard MBeans forexposing JVMs management to any interested management software.

JMX 2.0 (JSR 255): The new version ofJMX for Java 0 which introduces using generics, annotation,extended monitors, and so on.

Web Services Connector for JMX Agents(JSR 262): define an specification which leads to use Web Servicesto access JMX instrumentation remotely.

1.3 JMX benefits

What are JMX benefits that JCP defineda lot of JSRs for it and on top of it, why we did not followanother management standard like IEEE Std 828-1990. The reason isbehind the following JMX benefits:

Java needs an open to extend and closeto change API for integration with emerging requirement andtechnologies, JMX does this by its layered architecture.

The JMX is based on already welldefined and proven Java technologies like Java event model forproviding some of required functionalities.

The JMX specification andimplementation let us use it in any Java enabled software in anyscale.

Almost no change is required for anapplication to become manageable by JMX.

Many vendors uses Java to enable theirdevices, JMX provide one standard to manage both software andhardware.

You can imagine many other benefits forJMX which are not listed above.

1.4 Managed Beans (MBeans)

We discussed that generally there aretwo types of MBeans which we can choose to implement ourinstrumentation layer. Dynamic MBeans are a bit more complex and wewould rather skip them in this crash course, so in this section wewill discuss how MXBeans can be developed, used locally andremotely to prepare ourselves for understanding and using AMX tomanage GlassFish.

We said that we should write aninterface which defines all exposed operation of the MBeans bothfor the MXBeans and standard MBeans. So first we will write theinterface. Listing 1 shows the WorkerMXBean interface, theinterface has two methods which supposed to change a configurationin a worker thread and two properties which return the currentnumber of workers threads and maximum number of worker threads.Number of current workers thread is read only and maximum number ofthreads is both readable and updateable.

Listing 1 The MXBean interfacefor WorkerMXBean

@MXBean

public interface WorkerIF

{

public int getWorkersCount();

public int getMaxWorkers();

public void setMaxWorkers(intnewMaxWorkers);

public int stopAllWorkers();

}

I did not told you that we can forgetabout the naming conversion for MXBean interfaces if we areintended to use Java annotation. As you can see we simply markedthe interface as an MBean interface and defined some setter andgetter methods along with one operation which will stop someworkers and return the number of stopped workers.

The implementation of our MXBeaninterface will just implement some getter and setters along with adummy operation which just print a message in standard output.

Listing 2 the Worker MXBean implementation

public class Worker implements WorkerIF{

private int maxWorkers;

private int workersCount;

public Worker() {

}

public int getWorkersCount() {

return workersCount;

}

public int getMaxWorkers() {

return maxWorkers;

}

public void setMaxWorkers(intnewMaxWorkers) {

this.maxWorkers = newMaxWorkers;

}

public int stopAllWorkers() {

System.out.println(“Stopping allworkers”);

return 5;

}

}

We did not follow any naming conventionbecause we are using MXBean along with the annotation. If it was astandard MBean then we should have named the interface asWorkerMBean and the implementation class should have beenWorker.

Now we should register the MBean tosome MBean server to make it available to any management software.Listing 3 shows how we can develop a simple agent which will hostthe MBean server along with the registered MBeans.

Please replace the numbers with cueballs

Listing 3 How MBeans server works in a simple agent namedWorkerAgent

public class WorkerAgent {

public WorkerAgent() {

MBeanServer mbs =ManagementFactory.getPlatformMBeanServer(); #1

Worker workerBean = newWorker();                 #2

ObjectName workerName = null;

try {

workerName =new                               #3 ObjectName(“article:name=firstWorkerBean”);

mbs.registerMBean(workerBean,workerName);         #4

System.out.println(“Enter toexit…”);           #5

System.in.read();

} catch(Exception e) {

e.printStackTrace();

}

}

public static void main(String argv[]){

WorkerAgent agent = newWorkerAgent();

System.out.println(“Worker Agent isrunning…”);

}

}

At #1 we get the platform MBean Serverto register our MBean. Platform MBean server is the default JVMMBean server. At #2 we initialize an instance of our MBean.

At #3 we create a new ObjectName forour MBean. Each JVM may use many libraries which each of them canregister tens of MBeans, so MBeans should be uniquely identified inMBean server to prevent any naming collision. The ObjectName followa format to represent an MBean name in order to ensure that it isshown in a correct place in the management tree and lift anypossibility for naming conflict. An ObjectName is made up of twoparts, a domain and a name value pair separated by a colon. In ourcase the domain portion is article and the description isname=name=firstWorkerBean

At #4 as register the MBean to theMBean server. At #5 we just make sure that our application will notclose automatically and let us examine the MBean.

Sample code for this chapter isprovided along with the book, you can run the sample codes byfollowing the readme.txt file included in the chapter06 directoryof source code bundle. Using the sample code you will just useMaven to build and run the application and JConsole to monitor it.But the behind the scene procedure described in the followingparagraph.

To run the application and see how ourMBean will appear in a management console which is standardJConsole bundled with JDK. To enable the JMX management agent forlocal access we need to pass the -Dco

转载于:https://www.cnblogs.com/leeeee/p/7276718.html

你可能感兴趣的文章
c++中的string常用函数用法总结!
查看>>
[DLX精确覆盖+打表] hdu 2518 Dominoes
查看>>
SuperMap iServerJava 6R扩展领域开发及压力测试---判断点在那个面内(1)
查看>>
Week03-面向对象入门
查看>>
一个控制台程序,模拟机器人对话
查看>>
Vue 2.x + Webpack 3.x + Nodejs 多页面项目框架(上篇——纯前端多页面)
查看>>
我的PHP学习之路
查看>>
【题解】luogu p2340 奶牛会展
查看>>
对PostgreSQL的 SPI_prepare 的理解。
查看>>
解决响应式布局下兼容性的问题
查看>>
使用DBCP连接池对连接进行管理
查看>>
【洛谷】【堆+模拟】P2278 操作系统
查看>>
hdu3307 欧拉函数
查看>>
Spring Bean InitializingBean和DisposableBean实例
查看>>
[容斥][dp][快速幂] Jzoj P5862 孤独
查看>>
Lucene 学习之二:数值类型的索引和范围查询分析
查看>>
软件开发工作模型
查看>>
Java基础之字符串匹配大全
查看>>
面向对象
查看>>
lintcode83- Single Number II- midium
查看>>