1. 程式人生 > 程式設計 >spring boot 如何優雅關閉服務

spring boot 如何優雅關閉服務

spring boot 優雅的關閉服務

實現ContextClosedEvent 監聽器,監聽到關閉事件後,關閉springboot程序

**
網上有很多例子 使用spring boot 外掛做關閉經測試此外掛只能是關閉spring boot服務,不能殺死服務程序。還是需要實現關閉監聽,去殺死程序。
網上有很多例子 使用spring boot 外掛做關閉經測試此外掛只能是關閉spring boot服務,不能殺死服務程序。還是需要實現關閉監聽,去殺死程序。
網上有很多例子 使用spring boot 外掛做關閉經測試此外掛只能是關閉spring boot服務,不能殺死服務程序。還是需要實現關閉監聽,去殺死程序。

重要的事說三遍
**

actuator 關閉spring boot 實現方式
引入actuator 配置 shutdown
呼叫http://127.0.0.1/xxx/

引入actuator
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
  </dependency>-->

配置
在application.properties中開啟關閉
management.endpoints.web.exposure.include=*

#management.endpoint.shutdown.enabled = true

1.呼叫

1.主入口
	public static ConfigurableApplicationContext configurableApplicationContext;
	public static void main(String[] args) throws InterruptedException {
		 configurableApplicationContext = SpringApplication.run(GatewayApplication.class,args);
	}
	
2.關閉監聽
@Controller
	public static class ShutdownAction implements ApplicationListener<ContextClosedEvent> {
		@Override
		public void onApplicationEvent(ContextClosedEvent event) {
			System.exit(SpringApplication.exit(configurableApplicationContext));

		}
	}

3.關閉服務命令

 /**
  * 關閉服務
  */
 @RequestMapping(value = "/stop",method = RequestMethod.GET)
 @ResponseBody
 public void stopServer() {
  MySpringApplication.configurableApplicationContext.close();
 }

到此這篇關於spring boot 如何優雅關閉服務的文章就介紹到這了,更多相關spring boot 關閉服務 內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!