JMX의 간단한 회고

7644 단어 thread.netJ2SEsun
전에 JMX에 대해 알아봤는데 업무 중에 가끔 사용하기도 해요. 그런데 어떤 것을 체계적으로 배우지 않으면 마음이 공허해요. 그래서 이틀 동안 정돈을 했어요.코드를 좀 넣으세요. JMX규범의 구조도와 함께.
 
JMX 스키마:
 
 
package com.blackbeans.example.mbeans;

/**
 * Mbean  
 * @author blackbeans
 *
 */
public interface GunMBean {
	
	public void aimAndShoot(String[] targetName);
}

 
 
package com.blackbeans.example.mbeans;
import javax.management.AttributeChangeNotification;
import javax.management.NotificationBroadcasterSupport;

/**
 *    Mbean,    JMX Resources
 * 
 * @author blackbeans
 * 
 */
public class Gun extends NotificationBroadcasterSupport implements GunMBean {

	private String gunModel;

	public Gun(String gunModel) {
		this.gunModel = gunModel;
	}

	@Override
	public void aimAndShoot(String[] targetNames){
		
		for(String targetName : targetNames ){
		System.out.println(gunModel + "aim at "+ targetName +" !");
		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println(gunModel + " fire !");
		}
		
		AttributeChangeNotification notification = new AttributeChangeNotification(this, 0, 0L, "Gun shot!", null, null, null, null);

		sendNotification(notification);
		
	}
}

Mbean의 값 변화를 감시하기 위해 JMX의 에이전트 Level은 자바 이벤트를 기반으로 하는 Notification 메커니즘을 제공하여 다른 JMX의 현재 자원이 변경되었음을 알립니다.JMX의 Agent Level은 모니터 서비스를 제공하고 모든 Listener에게 알립니다.
 
 
package com.blackbeans.example.mbeans;

import javax.management.Notification;
import javax.management.NotificationListener;

public class GunFiredNotificationListener implements NotificationListener {

	@Override
	public void handleNotification(Notification notification, Object handback) {
		System.out.println("notifyInfo:\t"+notification+"
handback:\t"+handback); } }

 
   MBServer
 
package com.blackbeans.example.mbeans;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.MalformedURLException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;

public class MyMBeanServer {
	
	private MBeanServer mbServer;
	
	public MyMBeanServer()
	{
		this.mbServer = ManagementFactory.getPlatformMBeanServer();
		try {
			Registry reg = LocateRegistry.createRegistry(9999);
			for(String bind : reg.list()){
				System.out.println(bind);
			}
			JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://192.168.1.101:9999/MBServer");
			JMXConnectorServer connector = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbServer);
			connector.start();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	
	public void registerMBean(String objectName,Object obj)
	{
		ObjectName objName = null;
		try {
			objName = new ObjectName(objectName);
			this.mbServer.registerMBean(obj, objName);
			this.mbServer.addNotificationListener(objName, new GunFiredNotificationListener(), null, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public static void main(String[] args) throws InterruptedException {
		Gun gun = new Gun("AK-47");
		MyMBeanServer myServer = new MyMBeanServer();
		myServer.registerMBean(gun.getClass().getPackage().getName() + ":name="+gun.getClass().getSimpleName(), gun);
		Thread.sleep(100000);
	}
}

   MBeanClient
 
package com.blackbeans.example.mbeans;
import java.io.IOException;
import java.net.MalformedURLException;

import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;


public class MyMBeanClient{
	
	
	private MBeanServerConnection connection;
	public MyMBeanClient(String jmxUrl)
	{
		JMXServiceURL url = null;
		try {
			url = new JMXServiceURL(jmxUrl);
			JMXConnector connector = JMXConnectorFactory.connect(url);
			connector.connect();
			 this.connection = connector.getMBeanServerConnection();
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public void invokeMethod(ObjectName objName,String opName ,Object[] paras,String[] signature)
	{
		
		
		try {
			this.connection.invoke(objName, opName, paras, signature);
			
		} catch (InstanceNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MBeanException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ReflectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
			 
		String[] gunTypes = new String[]{"AK-47","M16"}; 
		
		MyMBeanClient client = new MyMBeanClient("service:jmx:rmi:///jndi/rmi://192.168.1.101:9999/MBServer");
		
		try {
			ObjectName objName = new ObjectName("com.blackbeans.example.mbeans:name=Gun");
			Object[] parameters = new Object[]{gunTypes};
			String[] signatures = new String[]{"[Ljava.lang.String;"};
			client.invokeMethod(objName, "aimAndShoot", parameters, signatures);
			
		} catch (MalformedObjectNameException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NullPointerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

 
나의 예에서 사용한 JMX의 RMI 호출은 물론 로컬 방식을 사용하거나 Sun의 HtmlJmxAdapter를 사용하여 JMX 호출을 완성하거나 클라이언트가 직접 jconsol을 사용하지 않고 연결하여 호출하면 된다.
 
reference:
                ht tp://java.sun.com/developer/technicalArticles/J2SE/jmx.html

좋은 웹페이지 즐겨찾기