ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

SpringBoot自动重启

SpringBoot自动重启

目录

  • 方法一:使用SpringCloud RestartEndpoint
  • 方法二:重新创建ApplicationContext上下文

方法一:使用SpringCloud RestartEndpoint

  • 使用的jar
    implementation 'org.springframework.boot:spring-boot-starter-actuator'implementation 'org.springframework.cloud:spring-cloud-starter-config:3.0.7'
  • 在application.properties添加配置
management.endpoint.restart.enabled=true
spring.cloud.config.enabled=false
  • 重启方法的Controller
import javax.annotation.Resource;import org.springframework.cloud.context.restart.RestartEndpoint;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/restart")
public class RestartController {@Resourceprivate RestartEndpoint restartEndpoint;@GetMapping("/restartApplication")public void restartApplication() {restartEndpoint.restart();}}

方法二:重新创建ApplicationContext上下文

  • 启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;@SpringBootApplication
public class Application {public static ConfigurableApplicationContext context;public static void main(String[] args) {context = SpringApplication.run(Application.class);}}
  • 重启方法的Controller
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import lombok.extern.slf4j.Slf4j;@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();}
}
返回列表