我需要:
- 什么是 JMX。
- 在哪里可以找到一些好的 JMX 教程。
- JMX 对作为 Java EE 程序员的我能提供什么。
- 我应该知道的其他任何内容。
我需要:
JMX是一种查看和操作应用程序运行状态的方式。如果有类似SNMP的概念,它与之有些相似。我认为,对于除了写入日志文件之外没有其他用户界面的服务器型应用程序来说,它是必不可少的监控和理解工具。
基本的方法是创建一个要监视的接口,然后让一个类实现该接口,最后将该类的实例注册到"MBeanServer"中(这实际上可以使在接口中定义的内容可供像jconsole这样的JMX监控应用程序使用)。
下面是一个微不足道但却有效的示例:
(假设使用Java 5或更高版本)
public interface TestServerMBean
{
public long getUptimeMillis();
public long getFooCount();
public void setFooCount(long val);
public void printStuff(String stuff);
}
import java.lang.management.ManagementFactory;
import java.util.concurrent.atomic.AtomicLong;
import javax.management.ObjectName;
// If jconsole doesn't see this app automatically, invoke the application with the following java flags, and connect
// 'remotely' via jconsole.
//
// -Dcom.sun.management.jmxremote
// -Dcom.sun.management.jmxremote.port=2222 (or whatever)
// -Dcom.sun.management.jmxremote.authenticate=false
// -Dcom.sun.management.jmxremote.ssl=false
public class TestServer implements TestServerMBean
{
private final AtomicLong m_counter = new AtomicLong(0L);
private final long m_startTimeMillis = System.currentTimeMillis();
public void run() throws InterruptedException {
while (true) {
m_counter.incrementAndGet();
Thread.sleep(5000);
}
}
public long getFooCount() {
return m_counter.get();
}
public void setFooCount(long val) {
m_counter.set(val);
}
public long getUptimeMillis() {
return System.currentTimeMillis() - m_startTimeMillis;
}
public void printStuff(String stuff) {
System.out.println(stuff);
}
public static void main(String[] args) throws Exception {
TestServer ts = new TestServer();
ManagementFactory.getPlatformMBeanServer().registerMBean(ts, new ObjectName("myapp:service=MyServer"));
ts.run();
}
}
显然,这是一个荒谬的“服务器”,但希望有一个简单的工作示例将有助于说明整体概念:能够窥视和操作正在运行的应用程序。
虽然有许多其他功能和不同类型的MBeans,但仅使用上述基本JMX功能就足以满足大多数需求。
jconsole
与Java一起,可以轻松地远程查看您的MBeans,而无需编写自己的客户端解决方案。您也可以使用自定义解决方案消耗MBeans,这可以给您极大的灵活性。这是我在初次了解JMX时阅读的两篇文章。
Sun教程:http://java.sun.com/docs/books/tutorial/jmx/index.html
Spring 2.5/JMX: http://static.springframework.org/spring/docs/2.5.x/reference/jmx.html
或者你可以在StackOverflow上查看JMX标签维基,我几天前更新了它,列出了你所要求的内容,还有一些额外的贡献信息: