Sfoglia il codice sorgente

增加了配置中心,用于保存公共的配置。

yangzhijie 5 anni fa
parent
commit
f65e4bd137

+ 6 - 0
pom.xml

@@ -51,6 +51,12 @@
 			<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
 		</dependency>
 
+		<!--sleuth日志跟踪-->
+		<dependency>
+		    <groupId>org.springframework.cloud</groupId>
+		    <artifactId>spring-cloud-starter-sleuth</artifactId>
+		</dependency>
+		
 		<!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
 		<dependency>
 		    <groupId>org.dom4j</groupId>

+ 12 - 33
src/main/java/com/leanwo/management/MainFrame.java

@@ -49,7 +49,7 @@ public class MainFrame extends JFrame{
 	private JButton startAllMenu = null;
 	private JButton stopAllMenu = null;
 
-	private JButton dbSettingMenu = null;
+	// private JButton dbSettingMenu = null;
 	
 	
 	private ServerFrame serverFrame = null;
@@ -88,7 +88,7 @@ public class MainFrame extends JFrame{
 		if(auto) {
 			FileUtil fileUtil = new FileUtil();
 			applicationSettingCache = new ApplicationSettingCache();
-			settings = fileUtil.getFile();
+			settings = fileUtil.getApplicationSettings();
 			applicationSettingCache.setSettings(settings);
 		}else {
 			applicationSettingCache = (ApplicationSettingCache) SpringUtil.getSingleBean(ApplicationSettingCache.class);
@@ -120,8 +120,8 @@ public class MainFrame extends JFrame{
         stopAllMenu = new JButton("全部关闭");
         toolbar.add(stopAllMenu);
         
-        dbSettingMenu = new JButton("数据源设置");
-        toolbar.add(dbSettingMenu);
+        //dbSettingMenu = new JButton("数据源设置");
+        //toolbar.add(dbSettingMenu);
         
         
 		serverFrame = new ServerFrame(settings);
@@ -250,40 +250,19 @@ public class MainFrame extends JFrame{
 		stopAllMenu.addActionListener(new ActionListener() {
 			@Override
 			public void actionPerformed(ActionEvent e) {
-				if (settings != null && settings.size() > 0) {
-					for(int i = 0; i < settings.size(); i ++) {
-						final ApplicationSetting setting = settings.get(i);
-						try {
-							ProgramRunResult programRunResult = setting.getProgramRunResult();
-							if(programRunResult != null && programRunResult.getProcess() != null) {
-								programRunResult.getProcess().destroyForcibly();
-							}
-							programRunResult = processService.stopProgram(setting);
-							if(programRunResult == null || programRunResult.getProcess() == null) {
-								logger.error(setting.getName() + "程序关闭异常,未配置停止文件。");
-							}else {
-								setting.setProgramRunResult(null);
-							}				
-						} catch (IOException e1) {
-							logger.error(setting.getName() +"程序关闭失败", e1);
-						}
-					}
-				}
+				processService.stopAll(settings);
 			}
 		});
 		
 
 		// 数据源设置
-		dbSettingMenu.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				DataSourceSettingFrame dataSourceSettingFrame = new DataSourceSettingFrame();
-				dataSourceSettingFrame.setVisible(true);
-			}
-		});
-		
-		
-		
+//		dbSettingMenu.addActionListener(new ActionListener() {
+//			@Override
+//			public void actionPerformed(ActionEvent e) {
+//				DataSourceSettingFrame dataSourceSettingFrame = new DataSourceSettingFrame();
+//				dataSourceSettingFrame.setVisible(true);
+//			}
+//		});
 	}
 	
 	/**

+ 3 - 0
src/main/java/com/leanwo/management/ServerFrame.java

@@ -183,6 +183,9 @@ public class ServerFrame extends JPanel {
 
 					setting.setOnline(online);
 					String status = online ? Variable.RUNNING : Variable.NOT_RUNNING;
+					if(online == false) {
+						setting.setStartSuccess(false);
+					}
 					
 					final int tempI = i;
 

+ 1 - 1
src/main/java/com/leanwo/management/ServerLogFrame.java

@@ -60,7 +60,7 @@ public class ServerLogFrame extends JPanel{
 				JPanel panel = new JPanel();
 				tabbedpane.addTab(tabNames[i],  panel);
 				
-				LogConsole logConsole = new LogConsole(tabNames[i]);
+				LogConsole logConsole = new LogConsole(tabNames[i], settings.get(i));
 				panel.setLayout(new GridLayout(1, 1));
 				panel.add(logConsole);
 				logConsoleMap.put(i, logConsole);

+ 24 - 3
src/main/java/com/leanwo/management/console/LogConsole.java

@@ -16,8 +16,15 @@ import javax.swing.JScrollPane;
 import javax.swing.JTextArea;
 import javax.swing.SwingUtilities;
 
-public class LogConsole extends JPanel{
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.leanwo.management.model.ApplicationSetting;
 
+public class LogConsole extends JPanel{
+	
+	private static final Logger logger = LoggerFactory.getLogger(LogConsole.class);
+	
 	private String name;
 	
 	private JTextArea textArea;
@@ -39,10 +46,13 @@ public class LogConsole extends JPanel{
 	/** 自动滚动 */
 	private boolean autoScroll;
 	
+	private ApplicationSetting setting;
+	
 	Clipboard clipboard;
 	
-	public LogConsole(String name) {
-		this.name = name;		
+	public LogConsole(String name, ApplicationSetting setting) {
+		this.name = name;	
+		this.setting = setting;
 		initData();
 		initView();
 	}
@@ -76,6 +86,11 @@ public class LogConsole extends JPanel{
 				@Override
 				public void appendLog(String data) {
 					LogConsole.this.appendLog(data);
+					
+					if(data.contains("启动成功")) {
+						setting.setStartSuccess(true);
+						logger.debug(setting.getName()+ "启动成功。");
+					}
 				}
 			} );
 			outReaderThread.setDaemon(true);	
@@ -86,6 +101,12 @@ public class LogConsole extends JPanel{
 				@Override
 				public void appendLog(String data) {
 					LogConsole.this.appendLog(data);
+					
+
+					if(data.contains("启动成功")) {
+						setting.setStartSuccess(true);
+						logger.debug(setting.getName()+ "启动成功。");
+					}
 				}
 			});	
 			errorReaderThread.setDaemon(true);	

+ 70 - 0
src/main/java/com/leanwo/management/model/ApplicationSetting.java

@@ -25,9 +25,18 @@ public class ApplicationSetting {
 	/** 停止程序BAT文件路径. */
 	private String stopBatFile;
 
+	/** 启动顺序(0-9)数值越小代表启动优先级越高. */
+	private Integer startSequence;
+
+	/** 显示顺序(0-9)数值越小代表越放在前面. */
+	private String showSequence;
+	
 	/** 应用程序是否在线(计算值). */
 	private boolean online;
 
+	/** 应用程序是否启动成功(计算值). */
+	private boolean startSuccess;
+	
 	/** 程序运行结果(计算值). */
 	private ProgramRunResult programRunResult;
 
@@ -103,6 +112,42 @@ public class ApplicationSetting {
 		this.stopBatFile = stopBatFile;
 	}
 
+	/**
+	 * Gets the 启动顺序(0-9)数值越小代表启动优先级越高.
+	 *
+	 * @return the 启动顺序(0-9)数值越小代表启动优先级越高
+	 */
+	public Integer getStartSequence() {
+		return startSequence;
+	}
+
+	/**
+	 * Sets the 启动顺序(0-9)数值越小代表启动优先级越高.
+	 *
+	 * @param startSequence the new 启动顺序(0-9)数值越小代表启动优先级越高
+	 */
+	public void setStartSequence(Integer startSequence) {
+		this.startSequence = startSequence;
+	}
+
+	/**
+	 * Gets the 显示顺序(0-9)数值越小代表越放在前面.
+	 *
+	 * @return the 显示顺序(0-9)数值越小代表越放在前面
+	 */
+	public String getShowSequence() {
+		return showSequence;
+	}
+
+	/**
+	 * Sets the 显示顺序(0-9)数值越小代表越放在前面.
+	 *
+	 * @param showSequence the new 显示顺序(0-9)数值越小代表越放在前面
+	 */
+	public void setShowSequence(String showSequence) {
+		this.showSequence = showSequence;
+	}
+
 	/**
 	 * Checks if is 应用程序是否在线(计算值).
 	 *
@@ -121,6 +166,24 @@ public class ApplicationSetting {
 		this.online = online;
 	}
 
+	/**
+	 * Checks if is 应用程序是否启动成功(计算值).
+	 *
+	 * @return the 应用程序是否启动成功(计算值)
+	 */
+	public boolean isStartSuccess() {
+		return startSuccess;
+	}
+
+	/**
+	 * Sets the 应用程序是否启动成功(计算值).
+	 *
+	 * @param startSuccess the new 应用程序是否启动成功(计算值)
+	 */
+	public void setStartSuccess(boolean startSuccess) {
+		this.startSuccess = startSuccess;
+	}
+
 	/**
 	 * Gets the 程序运行结果(计算值).
 	 *
@@ -130,6 +193,13 @@ public class ApplicationSetting {
 		return programRunResult;
 	}
 
+	@Override
+	public String toString() {
+		return "ApplicationSetting [name=" + name + ", installPath=" + installPath + ", startBatFile=" + startBatFile
+				+ ", stopBatFile=" + stopBatFile + ", startSequence=" + startSequence + ", showSequence=" + showSequence
+				+ ", online=" + online + ", startSuccess=" + startSuccess + "]";
+	}
+
 	/**
 	 * Sets the 程序运行结果(计算值).
 	 *

+ 101 - 10
src/main/java/com/leanwo/management/service/ProcessService.java

@@ -3,13 +3,17 @@ package com.leanwo.management.service;
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import com.leanwo.management.ServerLogFrame;
 import com.leanwo.management.model.ApplicationSetting;
+import com.leanwo.management.util.ThreadUtil;
 
 /**
  * 进程服务
@@ -20,6 +24,7 @@ public class ProcessService implements StatusService {
 	
 	private static Logger logger = LoggerFactory.getLogger(ProcessService.class);
 	
+	private Thread startAllThread = null;
 	/**
 	 * 启动新的程序
 	 * @param setting
@@ -110,27 +115,113 @@ public class ProcessService implements StatusService {
 	 * 程序自动运行
 	 */
 	public void autoStart(List<ApplicationSetting> settings, ServerLogFrame serverLogFrame) {
+		if(startAllThread != null) {
+			startAllThread.interrupt();
+			startAllThread = null;
+		}
+		// 1. 启动一个新的线程
+		Map<Integer, List<ApplicationSetting>> applicationSettingMap = new HashMap<Integer, List<ApplicationSetting>>();
+		Runnable startAllRunnable = new Runnable() {
+			@Override
+			public void run() {
+				// 2. 对settings根据启动优先级进行分组
+				if (settings != null && settings.size() > 0) {
+					for(int index = 0; index < 10; index ++) {
+						List<ApplicationSetting> applicationSettings = new ArrayList<ApplicationSetting>();
+						for(int i = 0; i < settings.size(); i ++) {
+							final ApplicationSetting setting = settings.get(i);
+							if(setting.getStartSequence() != null && setting.getStartSequence().equals(index)) {
+								applicationSettings.add(setting);
+							}
+							
+							if(index == 9 && setting.getStartSequence() == null) {
+								applicationSettings.add(setting);
+							}
+						}
+						applicationSettingMap.put(index, applicationSettings);
+					}
+				}
+				
+				// 3. 一个一个的启动
+				for(int index = 0; index < 10; index ++) {
+					List<ApplicationSetting> applicationSettings = applicationSettingMap.get(index);
+					if(applicationSettings != null && applicationSettings.size() > 0) {
+						for(int i = 0; i < applicationSettings.size(); i ++) {
+							if(startAllThread == null || (startAllThread != null && startAllThread.isInterrupted())) {
+								// 线程被中断,返回
+								return;
+							}
+							
+							final ApplicationSetting setting = applicationSettings.get(i);
+							ProgramRunResult programRunResult;
+							try {
+								programRunResult = startProgram(setting);
+								if(programRunResult != null && programRunResult.getProcess() != null) {
+									boolean isAlive = programRunResult.getProcess().isAlive();
+									if(! isAlive) {
+										logger.error("程序" + setting.getName() + "启动失败");
+									}
+									setting.setProgramRunResult(programRunResult);
+									serverLogFrame.updateProgramRunResult(settings.indexOf(setting), programRunResult);
+									
+									if(index < 9) {
+										// 顺序启动
+										while(setting.isStartSuccess() == false) {
+											ThreadUtil.sleep(1000L);
+											if(startAllThread == null || (startAllThread != null && startAllThread.isInterrupted())) {
+												// 线程被中断,返回
+												return;
+											}
+										}
+									}									
+								}
+							} catch (IOException e) {
+								logger.error("程序" + setting.getName() + "启动失败", e);
+							}
+						}
+					}
+				}
+			}
+		};
+		
+		startAllThread = new Thread(startAllRunnable);
+		startAllThread.start();
+	}
+	
+	/**
+	 * 停止所有的服务器
+	 * @param settings
+	 */
+	public void stopAll(List<ApplicationSetting> settings) {
+		if(startAllThread != null) {
+			startAllThread.interrupt();
+			startAllThread = null;
+		}
+		
 		if (settings != null && settings.size() > 0) {
 			for(int i = 0; i < settings.size(); i ++) {
 				final ApplicationSetting setting = settings.get(i);
-				ProgramRunResult programRunResult;
 				try {
-					programRunResult = startProgram(setting);
+					ProgramRunResult programRunResult = setting.getProgramRunResult();
 					if(programRunResult != null && programRunResult.getProcess() != null) {
-						boolean isAlive = programRunResult.getProcess().isAlive();
-						if(! isAlive) {
-							logger.error("程序" + setting.getName() + "启动失败");
-						}
-						setting.setProgramRunResult(programRunResult);
-						serverLogFrame.updateProgramRunResult(i, programRunResult);
+						programRunResult.getProcess().destroyForcibly();
 					}
-				} catch (IOException e) {
-					logger.error("程序" + setting.getName() + "启动失败", e);
+					programRunResult = stopProgram(setting);
+					if(programRunResult == null || programRunResult.getProcess() == null) {
+						logger.error(setting.getName() + "程序关闭异常,未配置停止文件。");
+					}else {
+						setting.setProgramRunResult(null);
+					}				
+				} catch (IOException e1) {
+					logger.error(setting.getName() +"程序关闭失败", e1);
 				}
 			}
 		}
+		
 	}
 	
+	
+	
 
 	/**
 	 * 获取服务器的状态

+ 34 - 14
src/main/java/com/leanwo/management/util/FileUtil.java

@@ -31,7 +31,7 @@ public class FileUtil {
 	 * 
 	 * @param closeables
 	 */
-	public List<ApplicationSetting> getFile() {
+	public List<ApplicationSetting> getApplicationSettings() {
 		List<ApplicationSetting> settings = new ArrayList<>();
 		File directory = new File("");
 		String path = directory.getAbsolutePath();
@@ -56,19 +56,34 @@ public class FileUtil {
 				if (!runFile.exists()) {
 					continue;
 				}
-				File stopFile = new File(filePath + "\\stop.bat");
-				if (!stopFile.exists()) {
-					continue;
-				}
-				String name = readFileContent(runFile);
-				name = name.replace("::", "").replace(" ", "").replace("echo", "").replace("title", "");
+//				File stopFile = new File(filePath + "\\stop.bat");
+//				if (!stopFile.exists()) {
+//					continue;
+//				}
+				String[] datas = readFileContent(runFile);
+				String name = ((datas == null || datas.length < 1 || datas[0] == null) ? "" : datas[0]);
+				name = name.trim().replace("::", "").replace(" ", "").replace("echo", "").replace("title", "");
 				if (name == null || name.length() <= 0) {
 					name = f.getName();
 				}
+				
+				String startSequenceStr = ((datas == null || datas.length < 2 || datas[1] == null) ? "" : datas[1]);
+				startSequenceStr = startSequenceStr.trim().replace("::", "").replace(" ", "").replace("echo", "").replace("title", "").replace("启动顺序", "");
+				try{
+					Integer startSequence = Integer.parseInt(startSequenceStr.trim());
+					applicationSetting.setStartSequence(startSequence);
+				}catch(Exception ex) {
+					logger.debug(name + "的第二行不是启动顺序。");
+				}
+				String showSequenceStr = ((datas == null || datas.length < 3 || datas[2] == null) ? "" : datas[2]);
+				showSequenceStr = showSequenceStr.trim().replace("::", "").replace(" ", "").replace("echo", "").replace("title", "").replace("菜单顺序", "");
+				applicationSetting.setShowSequence(showSequenceStr);
 				applicationSetting.setName(name);
 				applicationSetting.setInstallPath(filePath);
 				applicationSetting.setStartBatFile("run.bat");
 				applicationSetting.setStopBatFile("stop.bat");
+				
+				logger.debug(applicationSetting.toString());
 				settings.add(applicationSetting);
 			}
 		}
@@ -76,25 +91,30 @@ public class FileUtil {
 		Collections.sort(settings, new Comparator<ApplicationSetting>() {
 			@Override
 			public int compare(ApplicationSetting o1, ApplicationSetting o2) {
-				return o1.getName().compareTo(o2.getName());
+				return o1.getShowSequence().compareTo(o2.getShowSequence());
 			}
 		});
 
 		return settings;
 	}
 
-	public static String readFileContent(File file) {
+	public static String[] readFileContent(File file) {
 		BufferedReader reader = null;
-		StringBuffer sbf = new StringBuffer();
+		String[] datas = new String[3];
 		try {
 			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
-			String tempStr = reader.readLine();
-			sbf.append(tempStr);
+			datas[0] = reader.readLine();
+			datas[0] = (datas[0] == null) ? "" : datas[0];
+			datas[1] = reader.readLine();
+			datas[1] = (datas[1] == null) ? "" : datas[1];
+			datas[2] = reader.readLine();
+			datas[2] = (datas[2] == null) ? "" : datas[2];
+			
 //	        while ((tempStr = reader.readLine()) != null) {
 //	            sbf.append(tempStr);
 //	        }
 			reader.close();
-			return sbf.toString();
+			return datas;
 		} catch (IOException e) {
 			e.printStackTrace();
 		} finally {
@@ -106,6 +126,6 @@ public class FileUtil {
 				}
 			}
 		}
-		return sbf.toString();
+		return null;
 	}
 }

+ 9 - 7
src/main/resources/Application.yml

@@ -12,6 +12,7 @@ data-source:
       url: jdbc:sqlserver://127.0.0.1:1433;DatabaseName=ProdogAppAsset2020
       username: sa
       password: Sitp123123
+      
 spring:
   application:
     # 应用名称,会在Eureka中作为服务的id标识(serviceId)
@@ -21,22 +22,23 @@ spring:
 eureka:
   instance:
     prefer-ip-address: true
-    hostname: localhost
     #Eureka客户端向服务端发送心跳的时间间隔,单位为秒(客户端告诉服务端自己会按照该规则),默认30
-    lease-renewal-interval-in-seconds: 5
+    lease-renewal-interval-in-seconds: 2
     #Eureka服务端在收到最后一次心跳之后等待的时间上限,单位为秒,超过则剔除(客户端告诉服务端按照此规则等待自己),默认90
-    lease-expiration-duration-in-seconds: 10
+    lease-expiration-duration-in-seconds: 4
   server:
     # 关闭保护机制,默认true
     enable-self-preservation: false
     # 剔除失效服务间隔,默认60000
-    eviction-interval-timer-in-ms: 3000
+    eviction-interval-timer-in-ms: 4000
+    # Eureka Server 返回最新的注册信息的接口缓存刷新时间间隔,默认 30000(毫秒)
+    responseCacheUpdateIntervalMs: 2000
   client:
     #不拉取服务
-    fetch-registry: true
+    fetch-registry: false
     # 不注册自己
-    register-with-eureka: true
+    register-with-eureka: false
     # EurekaServer的地址,现在是自己的地址,如果是集群,需要写其它Server的地址。
     serviceUrl:
       #注册的地址,如果是集群,应该用,隔开
-      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
+      defaultZone: http://127.0.0.1:${server.port}/eureka/

+ 1 - 1
src/main/resources/autoRun.bat

@@ -1,4 +1,4 @@
 title ServerManagement
 cd /d %~dp0
 set current_path=%~dp0
-start javaw -jar %current_path%\ServerManagement.jar autoRun
+start javaw -jar -Xms64m -Xmx256m %current_path%\ServerManagement.jar autoRun

+ 5 - 4
src/main/resources/log4j2.xml

@@ -11,16 +11,17 @@
             <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
             <ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY"/>
             <!-- 这个都知道是输出日志的格式 -->
-            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss z} %-5level %class{36} [%L] [%M] - %msg%xEx%n"/>
+            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level [%logger{50}:%L] [%X{X-B3-TraceId},%X{X-B3-SpanId}] - %msg%n" />
+
         </Console>
         
 		<!-- 这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
 		<RollingFile name="RollingFile"
 			fileName="${LOG_HOME}/server-management.log"
 			filePattern="${LOG_HOME}/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
-			<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" />
-			<PatternLayout
-				pattern="%d{yyyy-MM-dd HH:mm:ss z} %-5level %class{36} [%L] [%M] - %msg%xEx%n" />
+			<ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY" />
+            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level [%logger{50}:%L] [%X{X-B3-TraceId},%X{X-B3-SpanId}] - %msg%n" />
+
 			<SizeBasedTriggeringPolicy size="2MB" />
 		</RollingFile>
 	</appenders>

+ 2 - 2
src/main/resources/run.bat

@@ -1,5 +1,5 @@
-:: 1.程序管理器
+:: 程序管理器
 title ServerManagement
 cd /d %~dp0
 set current_path=%~dp0
-start javaw -jar %current_path%\ServerManagement.jar
+start javaw -jar -Xms64m -Xmx256m %current_path%\ServerManagement.jar