远方蔚蓝
一刹那情真,相逢不如不见

文章数量 126

访问次数 199827

运行天数 1437

最近活跃 2024-10-04 23:36:48

进入后台管理系统

Springboot启动后执行逻辑与关闭前执行逻辑


方式1:
  1. 通过实现ApplicationRunner类,在程序启动后获取到Tomcat的端口
  1. 关闭程序关闭前需要执行关闭相关应用的占用
  1. 使用@PreDestroy注解需要在程序关闭前执行的方法
package wst.st.site.runner;
import java.lang.management.ManagementFactory;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.PreDestroy;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import javax.servlet.ServletContextEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.ContextLoaderListener;
/**
 * 程序启动后通过ApplicationRunner处理一些事务
 * @author wst 20191012日 上午10:37:29
 *
 */
//@Component
public class AfterApplicationRunner extends ContextLoaderListener implements ApplicationRunner {
	private Logger logger = LoggerFactory.getLogger(AfterApplicationRunner.class);
    @Value("${server.port}")
    private int port;
    @Value("${spring.profiles.active}")
    private String profile;
    
    private Boolean enabledConfigLog = true;
    @Autowired
    private ConfigurableApplicationContext configurableApplicationContext;
    @Override
    public void run(ApplicationArguments applicationArguments) {
    	String tomcatPort = this.getTomcatPort();
    	logger.info("部署完成,访问地址:http://localhost:" + (tomcatPort == null ? port : tomcatPort));
    }
    @Override
    public void contextInitialized(ServletContextEvent event) {
        if (null != enabledConfigLog && enabledConfigLog) {
        	logger.info("关键配置信息:");
            String[] activeProfiles = configurableApplicationContext.getEnvironment().getActiveProfiles();
            if (ObjectUtils.isEmpty(activeProfiles)) {
                String[] defaultProfiles = configurableApplicationContext.getEnvironment().getDefaultProfiles();
                logger.info("No active profile set, falling back to default profiles: " + StringUtils.arrayToCommaDelimitedString(defaultProfiles));
            } else {
            	logger.info("The following profiles are active: " + StringUtils.arrayToCommaDelimitedString(activeProfiles));
            }
            logger.info("Data Source:");
//            logger.info("  - url:{}", dataSourceProperties.getUrl());
//            logger.info("  - username:{}", dataSourceProperties.getUsername());
//            logger.info("  - password:{}", dataSourceProperties.getPassword());
            logger.info("Redis:");
//            logger.info("  - database:{}", redisProperties.getDatabase());
//            logger.info("  - host:{}", redisProperties.getHost());
//            logger.info("  - port:{}", redisProperties.getPort());
//            logger.info("  - password:{}", redisProperties.getPassword());
            
        }
    }
    
    private String getTomcatPort() {
		String port = null;
		try {
			MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
			Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
			if(objectNames != null) {
				Iterator<ObjectName> it = objectNames.iterator();
				while(it.hasNext()) {
					port = it.next().getKeyProperty("port");
					logger.info("获取外部tomcat端口: {}", port);
				}
			}
		} catch (MalformedObjectNameException e) {
			e.printStackTrace();
			logger.info("获取外部tomcat端口出错");
		}
		return port;
	}
    
    @PreDestroy
    public void destory(){
    	logger.info("在程序关闭后执行");
    }
}
方式2:
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.annotation.Configuration;
import com.goldpac.vtm.pre.socket.trade.InitProcessor;
/**
 * 
 * @author wst 20231011日 上午10:53:49
 *
 */
@Configuration
public class DisposableApplicationRunner implements DisposableBean {
	@Override
	public void destroy() throws Exception {
		// 关闭socket
		System.out.println("==========================>");
		InitProcessor.stopSocketHelper();
		System.out.println("==========================<");
	}
}