前言
大家好,這里是浩道Linux,主要給大家分享Linux、Python、網(wǎng)絡(luò)通信、網(wǎng)絡(luò)安全等相關(guān)的IT知識平臺。
相信不少Linux運維小伙伴在實際運維中經(jīng)常會用到kill -9 進程ID 這個命令來干掉程序。實際真的合理嗎,今天就讓我們一起來看看為什么技術(shù)牛人都不建議用kill -9關(guān)閉程序,看看該命令背后是咋樣的!
正文
kill -9 pid ???
kill可將指定的信息送至程序。預(yù)設(shè)的信息為SIGTERM(15),可將指定程序終止。若仍無法終止該程序,可使用SIGKILL(9)信息嘗試強制刪除程序。程序或工作的編號可利用ps指令或jobs指令查看(這段話來自菜鳥教程)。
講的這個復(fù)雜,簡單點來說就是用來殺死linux中的進程,啥?你問我啥是進程?請自行百度。
我相信很多人都用過kill -9 pid這個命令,徹底殺死進程的意思,一般情況我們使用它沒有上面問題,但是在我們項目中使用它就有可能存在致命的問題。
kill -9 pid 帶來的問題
由于kill -9 屬于暴力刪除,所以會給程序帶來比較嚴重的后果,那究竟會帶來什么后果呢?
舉個栗子:轉(zhuǎn)賬功能,再給兩個賬戶進行加錢扣錢的時候突然斷電了?這個時候會發(fā)生什么事情?對于InnoDB存儲引擎來說,沒有什么損失,因為它支持事務(wù),但是對于MyISAM引擎來說那簡直就是災(zāi)難,為什么?假如給A賬戶扣了錢,現(xiàn)在需要將B賬戶加錢,這個時候停電了,就會造成,A的錢被扣了,但是B沒有拿到這筆錢,這在生產(chǎn)環(huán)境是絕對不允許的,kill -9 相當于突然斷電的效果。
當然了,像轉(zhuǎn)賬這種,肯定不是使用MyISAM引擎,但是如今分布式火了起來,跨服務(wù)轉(zhuǎn)賬已經(jīng)是很平常的事情,這種時候如果使用kill -9 去停止服務(wù),那就不是你的事務(wù)能保證數(shù)據(jù)的準確性了,這個時候你可能會想到分布式事務(wù),這個世界上沒有絕對的安全系統(tǒng)或者架構(gòu),分布式事務(wù)也是一樣,他也會存在問題,概率很小,如果一旦發(fā)生,損失有可能是無法彌補的,所以一定不能使用kill -9 去停止服務(wù),因為你不知道他會造成什么后果。
在MyISAM引擎中表現(xiàn)的更明顯,比如用戶的信息由兩張表維護,管理員修改用戶信息的時候需要修改兩張表,但由于你的kill -9 暴力結(jié)束項目,導(dǎo)致只修改成功了一張表,這也會導(dǎo)致數(shù)據(jù)的不一致性,這是小事,因為大不了再修改一次,但是金錢、合同這些重要的信息如果由于你的暴力刪除導(dǎo)致錯亂,我覺得可能比刪庫跑路還嚴重,至少刪庫還能恢復(fù),你這個都不知道錯在哪里。
那我們應(yīng)該怎么結(jié)束項目呢?
其實java給我們提供了結(jié)束項目的功能,比如:tomcat可以使用shutdown.bat/shutdown.sh進行優(yōu)雅結(jié)束。
什么叫優(yōu)雅結(jié)束?
第一步:停止接收請求和內(nèi)部線程。
第二步:判斷是否有線程正在執(zhí)行。
第三步:等待正在執(zhí)行的線程執(zhí)行完畢。
第四步:停止容器。
以上四步才是正常的結(jié)束流程,那springboot怎么正常結(jié)束服務(wù)呢?下面我介紹幾種正常結(jié)束服務(wù)的方案,請拿好小本本做好筆記。
優(yōu)雅結(jié)束服務(wù)
kill -15 pid
這種方式也會比較優(yōu)雅的結(jié)束進程(項目),使用他的時候需要慎重,為什么呢?我們來看個例子
我寫了一個普通的controller方法做測試
@GetMapping(value="/test") publicStringtest(){ log.info("test---start"); try{ Thread.sleep(100000); }catch(InterruptedExceptione){ e.printStackTrace(); } log.info("test---end"); return"test"; } 1234567891011
代碼很簡單,打印:test — start之后讓讓程序休眠100秒,然后再打印:test — end,在線程休眠中我們使用kill -15 pid來結(jié)束這個進程,你們猜 test — end會被打印嗎?
application.yml
server: port:9988 12
啟動項目
sudo mvn spring-boot:run 1
這是maven啟動springboot項目的方式
看到這個就代表項目啟動成了
找到項目的進程id
sudo ps -ef |grep shutdown 1
這個就是項目的進程號,接下來我們先測試test接口,讓線程進入休眠狀態(tài),然后再使用kill -15 14086停止項目
sudo curl 127.0.0.1:9988/test 1
回到項目日志
我們發(fā)現(xiàn)請求已經(jīng)到達服務(wù),并且線程已經(jīng)成功進入休眠,現(xiàn)在我們kill -15 14086結(jié)束進程
sudo kill -15 14086 1
回到日志
2020-04-2410:53:14.939INFO14086---[nio-9988-exec-1]com.ymy.controller.TestController:test---start 2020-04-2410:54:02.450INFO14086---[extShutdownHook]o.s.s.concurrent.ThreadPoolTaskExecutor:ShuttingdownExecutorService'applicationTaskExecutor' java.lang.InterruptedException:sleepinterrupted atjava.lang.Thread.sleep(NativeMethod) atcom.ymy.controller.TestController.test(TestController.java:26) atsun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethod) atsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) atsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) atjava.lang.reflect.Method.invoke(Method.java:498) atorg.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) atorg.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) atorg.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) atorg.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) atorg.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) atorg.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) atorg.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) atorg.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) atorg.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) atorg.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) atjavax.servlet.http.HttpServlet.service(HttpServlet.java:634) atorg.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) atjavax.servlet.http.HttpServlet.service(HttpServlet.java:741) atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) atorg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) atorg.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) atorg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) atorg.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) atorg.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) atorg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) atorg.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) atorg.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) atorg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) atorg.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:109) atorg.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) atorg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) atorg.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) atorg.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) atorg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) atorg.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) atorg.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) atorg.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) atorg.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) atorg.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) atorg.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) atorg.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) atorg.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) atorg.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) atorg.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) atorg.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1594) atorg.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) atjava.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) atorg.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) atjava.lang.Thread.run(Thread.java:748) 2020-04-2410:54:04.574INFO14086---[nio-9988-exec-1]com.ymy.controller.TestController:test---end 2020-04-2410:54:04.610ERROR14086---[nio-9988-exec-1]o.s.web.servlet.HandlerExecutionChain:HandlerInterceptor.afterCompletionthrewexception java.lang.NullPointerException:null atorg.springframework.boot.actuate.metrics.web.servlet.LongTaskTimingHandlerInterceptor.stopLongTaskTimers(LongTaskTimingHandlerInterceptor.java:123)~[spring-boot-actuator-2.2.6.RELEASE.jar:2.2.6.RELEASE] atorg.springframework.boot.actuate.metrics.web.servlet.LongTaskTimingHandlerInterceptor.afterCompletion(LongTaskTimingHandlerInterceptor.java:79)~[spring-boot-actuator-2.2.6.RELEASE.jar:2.2.6.RELEASE] atorg.springframework.web.servlet.HandlerExecutionChain.triggerAfterCompletion(HandlerExecutionChain.java:179)~[spring-webmvc-5.2.5.RELEASE.jar:5.2.5.RELEASE] atorg.springframework.web.servlet.DispatcherServlet.triggerAfterCompletion(DispatcherServlet.java:1427)[spring-webmvc-5.2.5.RELEASE.jar:5.2.5.RELEASE] atorg.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)[spring-webmvc-5.2.5.RELEASE.jar:5.2.5.RELEASE] atorg.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)[spring-webmvc-5.2.5.RELEASE.jar:5.2.5.RELEASE] atorg.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)[spring-webmvc-5.2.5.RELEASE.jar:5.2.5.RELEASE] atorg.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)[spring-webmvc-5.2.5.RELEASE.jar:5.2.5.RELEASE] atjavax.servlet.http.HttpServlet.service(HttpServlet.java:634)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)[spring-webmvc-5.2.5.RELEASE.jar:5.2.5.RELEASE] atjavax.servlet.http.HttpServlet.service(HttpServlet.java:741)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)[tomcat-embed-websocket-9.0.33.jar:9.0.33] atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)[spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE] atorg.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)[spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE] atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)[spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE] atorg.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)[spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE] atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:109)[spring-boot-actuator-2.2.6.RELEASE.jar:2.2.6.RELEASE] atorg.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)[spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE] atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)[spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE] atorg.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)[spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE] atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1594)[tomcat-embed-core-9.0.33.jar:9.0.33] atorg.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)[tomcat-embed-core-9.0.33.jar:9.0.33] atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)[na:1.8.0_242] atjava.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)[na:1.8.0_242] atorg.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)[tomcat-embed-core-9.0.33.jar:9.0.33] atjava.lang.Thread.run(Thread.java:748)[na:1.8.0_242] 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
居然報錯了,但是test — end是打印出來了,為什么會報錯呢?這就和sleep這個方法有關(guān)了,在線程休眠期間,當調(diào)用線程的interrupt方法的時候會導(dǎo)致sleep拋出異常,這里很明顯就是kill -15 這個命令會讓程序馬上調(diào)用線程的interrupt方法,目的是為了讓線程停止,雖然讓線程停止,但線程什么時候停止還是線程自己說的算,這就是為什么我們還能看到:test — end的原因。
ConfigurableApplicationContext colse
我們先看怎么實現(xiàn)
packagecom.ymy.controller; importlombok.extern.slf4j.Slf4j; importorg.springframework.beans.BeansException; importorg.springframework.context.ApplicationContext; importorg.springframework.context.ApplicationContextAware; importorg.springframework.context.ConfigurableApplicationContext; importorg.springframework.web.bind.annotation.GetMapping; importorg.springframework.web.bind.annotation.PostMapping; importorg.springframework.web.bind.annotation.RestController; @RestController @Slf4j publicclassTestControllerimplementsApplicationContextAware{ privateApplicationContextcontext; @Override publicvoidsetApplicationContext(ApplicationContextapplicationContext)throwsBeansException{ this.context=applicationContext; } @GetMapping(value="/test") publicStringtest(){ log.info("test---start"); try{ Thread.sleep(100000); }catch(InterruptedExceptione){ e.printStackTrace(); } log.info("test---end"); return"test"; } /** *停機 */ @PostMapping(value="shutdown") publicvoidshutdown(){ ConfigurableApplicationContextcyx=(ConfigurableApplicationContext)context; cyx.close(); } } 1234567891011121314151617181920212223242526272829303132333435363738394041424344
重點在:cyx.close();,為什么他能停止springboot項目呢?請看源碼
publicvoidclose(){ synchronized(this.startupShutdownMonitor){ this.doClose(); if(this.shutdownHook!=null){ try{ Runtime.getRuntime().removeShutdownHook(this.shutdownHook); }catch(IllegalStateExceptionvar4){ } } } } 123456789101112
程序在啟動的時候向jvm注冊了一個關(guān)閉鉤子,我們在執(zhí)行colse方法的時候會刪除這個關(guān)閉鉤子,jvm就會知道這是需要停止服務(wù)。
我們看測試結(jié)果
很明顯,他也觸發(fā)了線程的interrupt方法導(dǎo)致線程報錯,原理和kill -15差不多。
actuator
這種方式是通過引入依賴的方式停止服務(wù),actuator提供了很多接口,比如健康檢查,基本信息等等,我們也可以使用他來優(yōu)雅的停機。
引入依賴
12345 org.springframework.boot spring-boot-starter-actuator
application.yml
server: port:9988 management: endpoints: web: exposure: include:shutdown endpoint: shutdown: enabled:true server: port:8888 12345678910111213
我這里對actuator的接口重新給定了一個接口,這樣可提高安全性,下面我們來測試一下
@RequestMapping(value="/test",method=RequestMethod.GET) publicStringtest(){ System.out.println("test---start"); try{ Thread.sleep(10000); }catch(InterruptedExceptione){ e.printStackTrace(); } System.out.println("test---end"); return"hello"; } 1234567891011
在請求test途中停止服務(wù)
我們發(fā)現(xiàn)發(fā)送停止服務(wù)請求之后還給我們返回了提示信息,很人性化,我們看看控制臺
test — end被執(zhí)行了,不過在停止線程池的時候還是調(diào)用了線程的interrupt方法,導(dǎo)致sleep報錯,這三種方式都可以比較優(yōu)雅的停止springboot服務(wù),如果我項目中存在線程休眠,我希望10秒以后再停止服務(wù)可以嗎?肯定是可以的,我們只需要稍微做點修改就可以了。
1.新增停止springboot服務(wù)類:ElegantShutdownConfig.java
packagecom.ymy.config; importorg.apache.catalina.connector.Connector; importorg.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer; importorg.springframework.context.ApplicationListener; importorg.springframework.context.event.ContextClosedEvent; importjava.util.concurrent.Executor; importjava.util.concurrent.ThreadPoolExecutor; importjava.util.concurrent.TimeUnit; publicclassElegantShutdownConfigimplementsTomcatConnectorCustomizer,ApplicationListener{ privatevolatileConnectorconnector; privatefinalintwaitTime=10; @Override publicvoidcustomize(Connectorconnector){ this.connector=connector; } @Override publicvoidonApplicationEvent(ContextClosedEventevent){ connector.pause(); Executorexecutor=connector.getProtocolHandler().getExecutor(); if(executorinstanceofThreadPoolExecutor){ try{ ThreadPoolExecutorthreadPoolExecutor=(ThreadPoolExecutor)executor; threadPoolExecutor.shutdown(); if(!threadPoolExecutor.awaitTermination(waitTime,TimeUnit.SECONDS)){ System.out.println("請嘗試暴力關(guān)閉"); } }catch(InterruptedExceptionex){ System.out.println("異常了"); Thread.currentThread().interrupt(); } } } } 1234567891011121314151617181920212223242526272829303132333435363738394041
2.在啟動類中加入bean
packagecom.ymy; importcom.ymy.config.ElegantShutdownConfig; importlombok.extern.slf4j.Slf4j; importorg.apache.catalina.connector.Connector; importorg.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer; importorg.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; importorg.springframework.boot.web.servlet.server.ServletWebServerFactory; importorg.springframework.context.ApplicationListener; importorg.springframework.context.ConfigurableApplicationContext; importorg.springframework.context.annotation.Bean; importorg.springframework.context.event.ContextClosedEvent; importjava.util.concurrent.Executor; importjava.util.concurrent.ThreadPoolExecutor; importjava.util.concurrent.TimeUnit; @SpringBootApplication publicclassShutdownServerApplication{ publicstaticvoidmain(String[]args){ ConfigurableApplicationContextrun=SpringApplication.run(ShutdownServerApplication.class,args); run.registerShutdownHook(); } @Bean publicElegantShutdownConfigelegantShutdownConfig(){ returnnewElegantShutdownConfig(); } @Bean publicServletWebServerFactoryservletContainer(){ TomcatServletWebServerFactorytomcat=newTomcatServletWebServerFactory(); tomcat.addConnectorCustomizers(elegantShutdownConfig()); returntomcat; } } 1234567891011121314151617181920212223242526272829303132333435363738394041
這樣我們就配置好了,我們再來測試一遍,test的接口還是休眠10秒
我們發(fā)現(xiàn)這次沒有報錯了,他是等待了一段時間之后再結(jié)束的線程池,這個時間就是我們在ElegantShutdownConfig類中配置的waitTime。
那可能你會有疑問了,jvm沒有立即停止,那這個時候在有請求會發(fā)生什么呢?如果關(guān)閉的時候有新的請求,服務(wù)將不在接收此請求。
數(shù)據(jù)備份操作
如果我想在服務(wù)停止的時候做點備份操作啥的,應(yīng)該怎么做呢?其實很簡單在你要執(zhí)行的方法上添加一個注解即可:@PreDestroy
“
Destroy:消滅、毀滅 pre:前綴縮寫
”
所以合在一起的意思就是在容器停止之前執(zhí)行一次,你可以在這里面做備份操作,也可以做記錄停機時間等。
新增服務(wù)停止備份工具類:DataBackupConfig.java
packagecom.ymy.config; importorg.springframework.context.annotation.Configuration; importjavax.annotation.PreDestroy; @Configuration publicclassDataBackupConfig{ @PreDestroy publicvoidbackData(){ System.out.println("正在備份數(shù)據(jù)。。。。。。。。。。。"); } } 123456789101112131415
我們再來測試然后打印控制臺日志:
審核編輯:湯梓紅
-
Linux
+關(guān)注
關(guān)注
87文章
11304瀏覽量
209498 -
程序
+關(guān)注
關(guān)注
117文章
3787瀏覽量
81043 -
命令
+關(guān)注
關(guān)注
5文章
684瀏覽量
22026 -
python
+關(guān)注
關(guān)注
56文章
4797瀏覽量
84688 -
kill
+關(guān)注
關(guān)注
0文章
9瀏覽量
2105
原文標題:為什么技術(shù)牛人都不建議用 kill -9 關(guān)閉程序?
文章出處:【微信號:浩道linux,微信公眾號:浩道linux】歡迎添加關(guān)注!文章轉(zhuǎn)載請注明出處。
發(fā)布評論請先 登錄
相關(guān)推薦
評論