package com.zy.core; import com.core.common.SpringUtils; import com.zy.core.plugin.api.MainProcessPluginApi; import com.zy.core.properties.SystemProperties; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; /** * WCS主流程 */ @Slf4j @Component public class MainProcess { @Value("${mainProcessPlugin}") private String mainProcessPlugin; private MainProcessPluginApi mainProcessPluginApi; // 所属线程 private volatile Thread thread; /** * =====>> 开始工作 */ public void start() { if (thread != null && thread.isAlive()) { log.warn("MainProcess is already running."); return; } thread = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { try { // 1. 加载插件 if (mainProcessPluginApi == null) { try { String className = mainProcessPlugin.contains(".") ? mainProcessPlugin : "com.zy.core.plugin." + mainProcessPlugin; Class clazz = Class.forName(className).asSubclass(MainProcessPluginApi.class); mainProcessPluginApi = SpringUtils.getBean(clazz); } catch (Exception e) { log.error("Failed to load mainProcessPlugin: {}", mainProcessPlugin, e); } } // 如果加载失败,等待后重试,防止空指针 if (mainProcessPluginApi == null) { Thread.sleep(3000); continue; } // 2. 系统运行状态判断 if (!SystemProperties.WCS_RUNNING_STATUS.get()) { // 防止忙等 (Busy-wait optimization) Thread.sleep(1000); continue; } // 3. 执行主流程 mainProcessPluginApi.run(); // 4. 间隔 Thread.sleep(200); } catch (InterruptedException ie) { log.info("MainProcess thread interrupted, stopping..."); Thread.currentThread().interrupt(); break; } catch (Exception e) { log.error("Error in MainProcess execution loop", e); try { // 避免异常导致的狂刷日志 Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } }); thread.setName("MainProcess"); thread.setDaemon(true); thread.start(); } @PreDestroy public void shutDown(){ if (thread != null) thread.interrupt(); } }