SPRINGBOOT在项目中重启

SPRINGBOOT在项目中重启

在生产环境中,直接频繁的去操作服务器是非常不可取的,所以若是能在项目中重启应用那就相当的方便。

  1. 通过启动类的写法
public static void main(String[] args) {
	SpringApplication.run(xxx.class, args);
}
// run方法其实是有一个 ConfigurableApplicationContext 类型的返回值 ,也就是上下文对象
// 上下文对象中有一个 close() 方法。该方法就能将springboot项目关闭

这个方法能够将应用关闭,但是如果想让项目重启的话,则需要另外的启动一个线程去操作。例如:

public static void restartApplication() {
		ApplicationArguments args = context.getBean(ApplicationArguments.class);

		Thread thread = new Thread(() -> {
			context.close();
            try {
                Thread.sleep(5000L);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            context = SpringApplication.run(SpringBootDemoHelloworldApplication.class, args.getSourceArgs());
		});

		thread.setDaemon(false);
		thread.start();
	}
// 此处写法参照 org.springframework.boot.actuate.context.ShutdownEndpoint (第二种写法)
  1. 通过引入spring-boot-actuator-**.jar
# web 应用首先需要引入,默认只引入 info、health 两个
management:
  endpoints:
    web:
      exposure:
        include: ["info","health","shutdown"]
    enabled-by-default: true  # 应用默认的规则
  endpoint:
    shutdown:
      enabled: true  开启shutdown

注意1:这里使用的是 spring actuator 进行项目关闭,此方法关闭时调用的是ShutdownEndpoint 中的 shutdown() 该方法被@WriteOperation 标注 也就意味着需要使用post方式发送请求才会生效。


	@WriteOperation
	public Map<String, String> shutdown() {
		if (this.context == null) {
			return NO_CONTEXT_MESSAGE;
		}
		try {
			return SHUTDOWN_MESSAGE;
		}
		finally {
			Thread thread = new Thread(this::performShutdown);
			thread.setContextClassLoader(getClass().getClassLoader());
			thread.start();
		}
	}


注意2:@EndPoint注解下的@ReadOperation, @WriteOperation, @DeleteOperation注解,分别对应生成Get/Post/Delete的Mapping。注解中有个produces参数,可以指定media type, 如:application/json等

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×