(자바JMX실습동영상)웹페이지에서 웹서버의 톰캣(Tomcat)시작/종료, 디스크공간 체크, 프로세스 KILL, 자바네트워크

(자바JMX실습동영상)웹페이지에서 웹서버의 톰캣(Tomcat)시작/종료, 디스크공간 체크, 프로세스 KILL, 자바네트워크 

 

-JmxMBean.java (MBean Interface 정의)
-Jmx.java (MBean Interface 구현체)
-JmxAgent.java (JMX Agent, 서버쪽 JMX Agent 구현)
-JmxClient.java(JMX Client, 클라이언트서비스 구현)
-
-JmxServlet.java(jsp요청을 처리할 서블릿)

 

-   jmx.jsp(테스트용 웹페이지)

 

52dc26f1b873924f06d2838808e2535e_1600209
 

 

 

0. eclipse dynamic web project 생성

   플젝명 : jmxweb1

 

1. web.xml

 

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://xmlns.jcp.org/xml/ns/javaee"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"

version="4.0">

<display-name>jmxweb1</display-name>

 

<servlet>

<servlet-name>jmxServlet</servlet-name>

<servlet-class>jmx.JmxServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>jmxServlet</servlet-name>

<url-pattern>/jmxServlet</url-pattern>

</servlet-mapping>

 

</web-app>

 

 

2. JmxNBean.java

 

package jmx;

 

public interface JmxMBean {

public void stopTomcat();

public void startTomcat();

public String getDiskCheck();

public void processKill(String processName);

}



3. Jmx.java

package jmx;

import java.io.File;

public class Jmx implements JmxMBean{
// 톰캣 실행 파일 경로
static String tomcatPath = "C:/dev/apache-tomcat-8.5.57/bin";

@Override
public void startTomcat() {
try {
    Process p =Runtime.getRuntime()
  .exec("cmd /c start " + tomcatPath + "/catalina.bat start", null, new File(tomcatPath));
    System.out.println("Tomcat Started(JMX.java) .....");
  } catch (Exception e) {
    System.err.println(e);
    System.out.println("Tomcat Start Error"+e.getMessage());
    e.printStackTrace();
  }
}
@Override
public void stopTomcat() {
try {
    Process p =Runtime.getRuntime()
    .exec("cmd /c start " + tomcatPath + "/catalina.bat stop", null, new File(tomcatPath));
    System.out.println("Tomcat Sopped(JMX.java).....");
  } catch (Exception e) {
    System.err.println(e);
    e.printStackTrace();
  }
}
@Override
public String getDiskCheck() {
String drive = null;
double totalSize = 0;
double freeSize = 0;
File[] roots = File.listRoots(); 
StringBuilder sb = new StringBuilder();
for (File root : roots) { 
        
    drive = root.getAbsolutePath();            
    totalSize = root.getTotalSpace() / Math.pow(1024, 3); 
    freeSize = root.getFreeSpace() / Math.pow(1024, 3);
    sb.append("Drive : " + drive + 
    " / TotalSize : " + Math.floor(totalSize) + 
    " / FreeSize : " + Math.floor(freeSize) +"\n");
System.out.println(sb.toString());
return sb.toString();

}
@Override
public void processKill(String processName){
Runtime rt = Runtime.getRuntime();
System.out.println("Process Killed(JMX.java) .....");
  try {
  rt.exec("taskkill /f /im " + processName);
} catch (Exception e) {
e.printStackTrace();
}
}
}


4. JmxAgent.java

package jmx;

import java.rmi.registry.LocateRegistry;

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

public class JmxAgent {
private MBeanServer mbs = null;
public JmxAgent() {
// 도메인명을 인자로 MBeanServer 생성
mbs = MBeanServerFactory.createMBeanServer("ServiceDomain");

// 구현된 MBean
Jmx jmxBean = new Jmx();
ObjectName mbeanName = null;
JMXServiceURL serviceUrl = null;
try {
LocateRegistry.createRegistry(7777);
serviceUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:7777/server");
mbeanName = new ObjectName("ServiceDomain:name=JmxMBean");
JMXConnectorServer connector = 
    JMXConnectorServerFactory.newJMXConnectorServer(serviceUrl, null, mbs);
mbs.registerMBean(jmxBean, mbeanName);
connector.start();
} catch(Exception e) {
e.printStackTrace();
}
}
private static void waitForEnterPressed() {
try {
System.out.println("Press to continue...");
System.in.read();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
new JmxAgent();
System.out.println("SimpleAgent is running...");
JmxAgent.waitForEnterPressed();
}
}


5. JmxClient.java
package jmx;

import java.io.IOException;

import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class JmxClient {

JMXServiceURL url = null;
JMXConnector jmxc = null;
MBeanServerConnection mbsc = null;
ObjectName mbeanName = null;
JmxMBean jmx = null;
public JmxClient() throws IOException, MalformedObjectNameException {
//JmxService URL
url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:7777/server");
jmxc = JMXConnectorFactory.connect(url, null); // JmxServiceURL에 연결
mbsc = jmxc.getMBeanServerConnection();         // MBeanServer에 연결
mbeanName = new ObjectName("ServiceDomain:name=JmxMBean");
// MBeanServer, mbeanName을 인자로 원격참조(MBean참조) 취득
jmx = JMX.newMBeanProxy(mbsc, mbeanName, JmxMBean.class, true);
}
public  void startTomcat() {
jmx.startTomcat();
}
public void stopTomcat() {
jmx.stopTomcat();
}
public String getDiskCheck() {
return jmx.getDiskCheck();
}
public void processKill(String processName) {
jmx.processKill(processName);
}
}


6. JmxServlet.java

package jmx;

import java.io.IOException;

import javax.management.MalformedObjectNameException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Jmx.jsp 웹페이지에서 요청을 받는 서블릿
 */
public class JmxServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {

String process = req.getParameter("process");
String command = req.getParameter("command");
JmxClient jmxClient = null;
try {
jmxClient = new JmxClient();
} catch (MalformedObjectNameException | IOException e) {
e.printStackTrace();
}
System.out.println(">>>>>>>>[JMXServlet POST] command ::: " + command);
if(command.equals("startTomcat")) {
jmxClient.startTomcat();
req.setAttribute("msg", "tomcat started...");
} else if (command.equals("stopTomcat")){
jmxClient.stopTomcat();
req.setAttribute("msg", "tomcat stopped...");
} else if (command.equals("getDiskCapacity")){
String content = jmxClient.getDiskCheck();
req.setAttribute("msg", content);
} else if (command.equals("killProcess")) {
jmxClient.processKill(process);
req.setAttribute("msg", "process killed...");
}
RequestDispatcher rd = getServletContext().getRequestDispatcher("/jmx.jsp");
rd.forward(req, resp);
}
}


7. jmx.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="jmx.JmxClient" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JMX</title>
<%
String path=request.getContextPath();
String msg = "";
if(request.getAttribute("msg") != null) {
msg = (String) request.getAttribute("msg");
}
%>
<script type="text/javascript">
function stopTomcat() {
document.frm.command.value = 'stopTomcat';  
document.frm.action = "<%=path %>/jmxServlet";
document.frm.submit();
}

function startTomcat() {
document.frm.command.value = 'startTomcat';
document.frm.action = "<%=path %>/jmxServlet";
document.frm.submit();
}

function getDiskCheck() {
document.frm.command.value = 'getDiskCapacity';
document.frm.action = "<%=path %>/jmxServlet";
document.frm.submit();
}

function processKill() {
document.frm.command.value = 'killProcess';
var processName = null;
if(document.frm.process.value == null || document.frm.process.value == "") {
alert("kill할 process를 입력해주세요.");
return false;
} else {
processName = document.frm.process.value;
document.frm.action = "<%=path %>/jmxServlet";
document.frm.submit();
}
}
</script>
</head>
<body>
<form id="frm" name="frm" method="POST">
<input type="hidden" id="command" name="command" value=""/>
    <P>주의 : 현재 실행중인 Tomcat이 아닌 다른  Tomcat 서버로 테스트 하세요</P>
<button onclick="startTomcat()">웹서버쪽 톰캣시작</button>
<button onclick="stopTomcat()">웹서버쪽 톰캣종료</button>
<br/>
<button onclick="getDiskCheck()">웹서버용량확인</button>
<br/>
프로세스명 :  <input type="text" id="process" name="process"/>
<button onclick="processKill()">웹서버쪽 프로세스 죽이기</button>
<br/>
<textarea rows="8" cols="100" name="contents"><%=msg%></textarea>
</form>
</body>
</html>


8.실행

톰캣기동 : localhost:8080/jmxweb1/kmx.jsp

JmxAgent 기동 : JmxAgent.java 실행  run as , java application

#자바JMX, #JMX톰캣, #JMXWAS, #JMX강의, #JMX강좌, #JMX동영상, #JMX예제, #JMX교육, #자바네트워크, #자바, #JAVA, #JMX, #자바동영상, #JAVA동영상, #JMX란, #자바JMX동영상



 

 

 

 

 

 

 

Comments