jmx helloworld简版
2020-05-26 本文已影响0人
simplerandom
public class Task implements TaskMBean {
String name;
String state="初始状态";
public Task(String name) {
this.name = name;
}
@Override
public String setState(String state) {
this.state=state;
return this.name+"状态设置为"+state;
}
@Override
public String setName(String name) {
this.name=name;
return this.name+"名字设置为"+name;
}
@Override
public String getState() {
return this.name+"的状态为"+this.state;
}
@Override
public String getName() {
return this.name+"的名字为"+this.name;
}
}
public interface TaskMBean {
String setState(String state);
String setName(String name);
String getState();
String getName();
}
public class TaskAgent {
public static void main(String[] args)
throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException,
MBeanRegistrationException, IOException {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName objectName=new ObjectName("taskDomain","name","task");
ObjectInstance instance = mBeanServer.registerMBean(new Task("测试任务"), objectName);
LocateRegistry.createRegistry(9999);
//URL路径的结尾可以随意指定,但如果需要用Jconsole来进行连接,则必须使用jmxrmi
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/taskDomain");
JMXConnectorServer jcs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mBeanServer);
System.out.println("begin rmi start");
jcs.start();
System.out.println("rmi start");
}
}
public class JmxClient {
public static void main(String[] args)
throws IOException, MalformedObjectNameException, AttributeNotFoundException, MBeanException,
ReflectionException, InstanceNotFoundException, IntrospectionException, InvalidAttributeValueException {
//begin固定写法
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/taskDomain");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
//end
ObjectName mbeanName = new ObjectName("taskDomain:name=task");
// 调用getName方法,Name大写否则报错
String state = (String) mbsc.getAttribute(mbeanName, "State");
System.out.println(state);
// 通过代理对象调用可放置无权限
// 且更直观
TaskMBean proxy = MBeanServerInvocationHandler.
newProxyInstance(mbsc, mbeanName, TaskMBean.class, false);
String name = proxy.setName("proxy任务");
System.out.println(name);
String state1 = proxy.setState("进行中");
System.out.println(state1);
}
}