方式一:通过重新创建上下文进行重启
实现:
spring boot启动类
@SpringBootApplication public class Application { public static ConfigurableApplicationContext context; public static void main(String[] args) { context = SpringApplication.run(Application.class); } }
重启方法的Controller
@Slf4j @RestController @RequestMapping("/restart") public class RestartController { private static void restart() { ApplicationArguments args = Application.context.getBean(ApplicationArguments.class); Thread thread = new Thread(() -> { log.info("springboot restart..."); Application.context.close(); Application.context = SpringApplication.run(Application.class, args.getSourceArgs()); }); // 设置为用户线程,不是守护线程 thread.setDaemon(false); thread.start(); } }
方式二:利用执行器的重启端点RestartEndpoint.restart()进行重启
实现:
pom.xml
<!--重启--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> <version>2.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter</artifactId> <version>2.2.2.RELEASE</version> </dependency>
application.yml
# 重启management: endpoint: restart: enabled: true # 启用内置重启端点
java实现
@Resource RestartEndpoint restartEndpoint; /** * 调用该方法即可完成应用重启 */ public void restartApplication() { restartEndpoint.restart(); }
文章版权声明:除非注明,否则均为白茶清欢的个人技术分享原创文章,转载或复制请以超链接形式并注明出处。
发表评论