我想创建一个可以与我的服务器一起使用的JMX客户端。我可以用jconsole连接到我的服务器,但是我怎么能用java代码呢。 谢谢!
这是我的服务器代码:
MBeanServer mbeanServer = ManagementFactory
.getPlatformMBeanServer();
//giving name for service
ObjectName objectName = new ObjectName("bean:name=logService");
RequiredModelMBean mbean = new RequiredModelMBean();
mbean.setManagedResource(logService, "objectReference");
Descriptor logStringDescriptor = new DescriptorSupport(
new String[] { "name=logString",
"descriptorType=attribute",
"getMethod=getLogString", "setMethod=setLogString" });
ModelMBeanAttributeInfo logStringAttribute = new ModelMBeanAttributeInfo(
"logString", "java.lang.String", "String to be logged",
true, true, false, logStringDescriptor);
ModelMBeanOperationInfo getLogStringOperation = new ModelMBeanOperationInfo(
"Get the log string",
LoggerService.class.getMethod("getLogString"));
ModelMBeanOperationInfo setLogStringOperation = new ModelMBeanOperationInfo(
"Set the log string", LoggerService.class.getMethod(
"setLogString", String.class));
ModelMBeanInfo mbeanInfo = new ModelMBeanInfoSupport(
"LoggerService", "Logger Service",
new ModelMBeanAttributeInfo[] { logStringAttribute }, null,
new ModelMBeanOperationInfo[] { getLogStringOperation,
setLogStringOperation }, null);
mbean.setModelMBeanInfo(mbeanInfo);
mbeanServer.registerMBean(mbean, objectName);
答案 0 :(得分:1)
很简单:)
MBeanServer mbeanServer = ManagementFactory
.getPlatformMBeanServer();
//giving name for service
ObjectName objectName = new ObjectName("bean:name=logService");
String str = (String) mbeanServer.getAttribute (objectName, "logString");
System.out.println(str);
答案 1 :(得分:0)
您必须创建一个JMX代理,它将作为MBean服务器的包装器,并允许外部进程使用特殊适配器连接到您的应用程序。此适配器将允许您的客户端使用特定协议(SNMP,HTTP等)或技术(RMI)连接到MBean服务器。您可以在此处阅读有关适配器的信息:http://marxsoftware.blogspot.com/2008/08/remote-jmx-connectors-and-adapters.html
答案 2 :(得分:0)
public static <T> T createJmxClient(Class<T> clazz, String objectName, String serviceUrl) {
return createJmxClient(clazz, objectName, serviceUrl, null, null);
}
public static <T> T createJmxClient(Class<T> clazz, String objectName, String serviceUrl, final String user, final String pass) {
try {
JMXServiceURL jmxServiceUrl = new JMXServiceURL(serviceUrl);
Map<String, ?> env = user == null ? null : new HashMap<String, Object>() {{
put(JMXConnector.CREDENTIALS, new String[] {user, pass});
}};
JMXConnector jmxc = JMXConnectorFactory.connect(jmxServiceUrl, env);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
ObjectName mbeanName = new ObjectName(objectName);
return JMX.newMBeanProxy(mbsc, mbeanName, clazz, true);
} catch (IOException | MalformedObjectNameException e) {
throw new RuntimeException("Can not create client for remote JMX " + serviceUrl, e);
}
}