Spring Boot 2.X優雅中止

本文章介紹了正常關閉Spring Boot 應用程序的過程。許多開發人員和架構師老是討論SpringBoot的應用設計、流量負載、框架和應用模式,但不多有人討論關閉階段。生命週期意識能夠說一個真正資深程序員應該具備的素質,對於重資源對象,包括線程池 鏈接池等都要善始善終,不能只顧建立。html

對於 SpringBoot 來講,打包成一個簡單的 Jar 包直接使用 java -jar便可啓動,這是一種很是優雅的方式,但同時也帶來了必定的問題,如:應用如何中止?在過去,應用程序是部署在特定的容器中的,使用容器提供的腳本能夠優雅停服,但如今容器被內嵌了,腳本沒有了,怎麼辦?直接 kill 是一種方式,但未免顯得太過粗魯,並且可能帶來許多意想不到的問題。java


下面記錄一種方案。程序員

使用 Endpoints

在 SpringBoot 官方文檔的第5部分中介紹了爲應用發佈生產準備的各類特性,其中,經過 Actuator 的 HTTP Endpoint,開發人員能夠方便地對應用的監控與管理。此方法配合winsw使用,適用於window服務器,有須要請參考:在windows服務器上使用winsw部署spring boot項目web

引入指定的SpringBoot starter包spring

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

在 application.properties 中打開以下兩個配置,便可實現經過 Http 請求中止應用windows

management.endpoints.web.exposure.include=*
management.endpoint.shutdown.enabled=true

操做命令以下:安全

curl -X POST http://host:port/actuator/shutdown

但這種方式有一個很是嚴重的問題,那就是任意人均可以控制應用的中止,爲了保證系統的安全,須要給其加上一層 HTTP Basic Authbash

增長 Security 依賴:服務器

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

在 application.properties 中增長以下兩個配置:架構

spring.security.user.name=actuator
spring.security.user.password=password
spring.security.user.roles=ACTUATOR

增長security過濾規則

@Configuration
public class ActuatorWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable().authorizeRequests().antMatchers("/").permitAll()
		.requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ACTUATOR")
        .anyRequest().authenticated().and()
        //開啓basic認證,若不添加此項,將不能經過curl的basic方式傳遞用戶信息
        .httpBasic();
	}

}

配置完成後,最終的停服命令爲:

curl -X POST -u actuator:password http://host:port/actuator/shutdown

執行返回:{"message":"Shutting down, bye..."},說明服務中止成功。

相關文章
相關標籤/搜索