现在有一个需求,是定时任务执行扫描,判断如果端口有变化,需要重启项目。思路是通过关闭应用程序上下文并从头创建一个新上下文来重新启动应用程序。具体代码如下:
1. 启动类定义重启方法
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
/**
* @author:
* @date: 2023-02-03 14:20
* @description: agent的启动类
*/
@SpringBootApplication
public class AgentApplication {
private static ConfigurableApplicationContext context;
public static void main(String[] args) {
context = SpringApplication.run(AgentApplication.class, args);
}
/**
* 重启服务
*/
public static void restart() {
ApplicationArguments args = context.getBean(ApplicationArguments.class);
Thread thread = new Thread(() -> {
context.close();
context = SpringApplication.run(AgentApplication.class, args.getSourceArgs());
});
// 设置非守护线程
thread.setDaemon(false);
thread.start();
}
}
2. 定时任务调用代码
import com.wrdxa.agent.AgentApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/**
* @author:
* @date: 2023-02-03 16:19
* @description: 定时任务的类
*/
@Configuration
@EnableScheduling
public class ScheduleTask {
/**
* 每隔1分钟执行一次查询,如果监测有变化,则进行重启
*/
@Scheduled(cron = "*/30 * * * * ?")
private void configureTasks() {
System.out.println("开始重启");
AgentApplication.restart();
}
}