前言
大家好,這里是浩道Linux,主要給大家分享Linux、Python、網(wǎng)絡(luò)通信、網(wǎng)絡(luò)安全等相關(guān)的IT知識(shí)平臺(tái)。
相信不少Linux運(yùn)維小伙伴在實(shí)際運(yùn)維中經(jīng)常會(huì)用到kill -9 進(jìn)程ID 這個(gè)命令來(lái)干掉程序。實(shí)際真的合理嗎,今天就讓我們一起來(lái)看看為什么技術(shù)牛人都不建議用kill -9關(guān)閉程序,看看該命令背后是咋樣的!
正文
kill -9 pid ???
kill可將指定的信息送至程序。預(yù)設(shè)的信息為SIGTERM(15),可將指定程序終止。若仍無(wú)法終止該程序,可使用SIGKILL(9)信息嘗試強(qiáng)制刪除程序。程序或工作的編號(hào)可利用ps指令或jobs指令查看(這段話來(lái)自菜鳥(niǎo)教程)。
講的這個(gè)復(fù)雜,簡(jiǎn)單點(diǎn)來(lái)說(shuō)就是用來(lái)殺死linux中的進(jìn)程,啥?你問(wèn)我啥是進(jìn)程?請(qǐng)自行百度。
我相信很多人都用過(guò)kill -9 pid這個(gè)命令,徹底殺死進(jìn)程的意思,一般情況我們使用它沒(méi)有上面問(wèn)題,但是在我們項(xiàng)目中使用它就有可能存在致命的問(wèn)題。
kill -9 pid 帶來(lái)的問(wèn)題
由于kill -9 屬于暴力刪除,所以會(huì)給程序帶來(lái)比較嚴(yán)重的后果,那究竟會(huì)帶來(lái)什么后果呢?
舉個(gè)栗子:轉(zhuǎn)賬功能,再給兩個(gè)賬戶進(jìn)行加錢扣錢的時(shí)候突然斷電了?這個(gè)時(shí)候會(huì)發(fā)生什么事情?對(duì)于InnoDB存儲(chǔ)引擎來(lái)說(shuō),沒(méi)有什么損失,因?yàn)樗С质聞?wù),但是對(duì)于MyISAM引擎來(lái)說(shuō)那簡(jiǎn)直就是災(zāi)難,為什么?假如給A賬戶扣了錢,現(xiàn)在需要將B賬戶加錢,這個(gè)時(shí)候停電了,就會(huì)造成,A的錢被扣了,但是B沒(méi)有拿到這筆錢,這在生產(chǎn)環(huán)境是絕對(duì)不允許的,kill -9 相當(dāng)于突然斷電的效果。
當(dāng)然了,像轉(zhuǎn)賬這種,肯定不是使用MyISAM引擎,但是如今分布式火了起來(lái),跨服務(wù)轉(zhuǎn)賬已經(jīng)是很平常的事情,這種時(shí)候如果使用kill -9 去停止服務(wù),那就不是你的事務(wù)能保證數(shù)據(jù)的準(zhǔn)確性了,這個(gè)時(shí)候你可能會(huì)想到分布式事務(wù),這個(gè)世界上沒(méi)有絕對(duì)的安全系統(tǒng)或者架構(gòu),分布式事務(wù)也是一樣,他也會(huì)存在問(wèn)題,概率很小,如果一旦發(fā)生,損失有可能是無(wú)法彌補(bǔ)的,所以一定不能使用kill -9 去停止服務(wù),因?yàn)槟悴恢浪麜?huì)造成什么后果。
在MyISAM引擎中表現(xiàn)的更明顯,比如用戶的信息由兩張表維護(hù),管理員修改用戶信息的時(shí)候需要修改兩張表,但由于你的kill -9 暴力結(jié)束項(xiàng)目,導(dǎo)致只修改成功了一張表,這也會(huì)導(dǎo)致數(shù)據(jù)的不一致性,這是小事,因?yàn)榇蟛涣嗽傩薷囊淮?,但是金錢、合同這些重要的信息如果由于你的暴力刪除導(dǎo)致錯(cuò)亂,我覺(jué)得可能比刪庫(kù)跑路還嚴(yán)重,至少刪庫(kù)還能恢復(fù),你這個(gè)都不知道錯(cuò)在哪里。
那我們應(yīng)該怎么結(jié)束項(xiàng)目呢?
其實(shí)java給我們提供了結(jié)束項(xiàng)目的功能,比如:tomcat可以使用shutdown.bat/shutdown.sh進(jìn)行優(yōu)雅結(jié)束。
什么叫優(yōu)雅結(jié)束?
第一步:停止接收請(qǐng)求和內(nèi)部線程。
第二步:判斷是否有線程正在執(zhí)行。
第三步:等待正在執(zhí)行的線程執(zhí)行完畢。
第四步:停止容器。
以上四步才是正常的結(jié)束流程,那springboot怎么正常結(jié)束服務(wù)呢?下面我介紹幾種正常結(jié)束服務(wù)的方案,請(qǐng)拿好小本本做好筆記。
優(yōu)雅結(jié)束服務(wù)
kill -15 pid
這種方式也會(huì)比較優(yōu)雅的結(jié)束進(jìn)程(項(xiàng)目),使用他的時(shí)候需要慎重,為什么呢?我們來(lái)看個(gè)例子
我寫(xiě)了一個(gè)普通的controller方法做測(cè)試
@GetMapping(value="/test") publicStringtest(){ log.info("test---start"); try{ Thread.sleep(100000); }catch(InterruptedExceptione){ e.printStackTrace(); } log.info("test---end"); return"test"; } 1234567891011
代碼很簡(jiǎn)單,打?。簍est — start之后讓讓程序休眠100秒,然后再打?。簍est — end,在線程休眠中我們使用kill -15 pid來(lái)結(jié)束這個(gè)進(jìn)程,你們猜 test — end會(huì)被打印嗎?
application.yml
server: port:9988 12
啟動(dòng)項(xiàng)目
sudo mvn spring-boot:run 1
這是maven啟動(dòng)springboot項(xiàng)目的方式
看到這個(gè)就代表項(xiàng)目啟動(dòng)成了
找到項(xiàng)目的進(jìn)程id
sudo ps -ef |grep shutdown 1
這個(gè)就是項(xiàng)目的進(jìn)程號(hào),接下來(lái)我們先測(cè)試test接口,讓線程進(jìn)入休眠狀態(tài),然后再使用kill -15 14086停止項(xiàng)目
sudo curl 127.0.0.1:9988/test 1
回到項(xiàng)目日志
我們發(fā)現(xiàn)請(qǐng)求已經(jīng)到達(dá)服務(wù),并且線程已經(jīng)成功進(jìn)入休眠,現(xiàn)在我們kill -15 14086結(jié)束進(jìn)程
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
居然報(bào)錯(cuò)了,但是test — end是打印出來(lái)了,為什么會(huì)報(bào)錯(cuò)呢?這就和sleep這個(gè)方法有關(guān)了,在線程休眠期間,當(dāng)調(diào)用線程的interrupt方法的時(shí)候會(huì)導(dǎo)致sleep拋出異常,這里很明顯就是kill -15 這個(gè)命令會(huì)讓程序馬上調(diào)用線程的interrupt方法,目的是為了讓線程停止,雖然讓線程停止,但線程什么時(shí)候停止還是線程自己說(shuō)的算,這就是為什么我們還能看到:test — end的原因。
ConfigurableApplicationContext colse
我們先看怎么實(shí)現(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"; } /** *停機(jī) */ @PostMapping(value="shutdown") publicvoidshutdown(){ ConfigurableApplicationContextcyx=(ConfigurableApplicationContext)context; cyx.close(); } } 1234567891011121314151617181920212223242526272829303132333435363738394041424344
重點(diǎn)在:cyx.close();,為什么他能停止springboot項(xiàng)目呢?請(qǐng)看源碼
publicvoidclose(){ synchronized(this.startupShutdownMonitor){ this.doClose(); if(this.shutdownHook!=null){ try{ Runtime.getRuntime().removeShutdownHook(this.shutdownHook); }catch(IllegalStateExceptionvar4){ } } } } 123456789101112
程序在啟動(dòng)的時(shí)候向jvm注冊(cè)了一個(gè)關(guān)閉鉤子,我們?cè)趫?zhí)行colse方法的時(shí)候會(huì)刪除這個(gè)關(guān)閉鉤子,jvm就會(huì)知道這是需要停止服務(wù)。
我們看測(cè)試結(jié)果
很明顯,他也觸發(fā)了線程的interrupt方法導(dǎo)致線程報(bào)錯(cuò),原理和kill -15差不多。
actuator
這種方式是通過(guò)引入依賴的方式停止服務(wù),actuator提供了很多接口,比如健康檢查,基本信息等等,我們也可以使用他來(lái)優(yōu)雅的停機(jī)。
引入依賴
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
我這里對(duì)actuator的接口重新給定了一個(gè)接口,這樣可提高安全性,下面我們來(lái)測(cè)試一下
@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
在請(qǐng)求test途中停止服務(wù)
我們發(fā)現(xiàn)發(fā)送停止服務(wù)請(qǐng)求之后還給我們返回了提示信息,很人性化,我們看看控制臺(tái)
test — end被執(zhí)行了,不過(guò)在停止線程池的時(shí)候還是調(diào)用了線程的interrupt方法,導(dǎo)致sleep報(bào)錯(cuò),這三種方式都可以比較優(yōu)雅的停止springboot服務(wù),如果我項(xiàng)目中存在線程休眠,我希望10秒以后再停止服務(wù)可以嗎?肯定是可以的,我們只需要稍微做點(diǎn)修改就可以了。
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("請(qǐng)嘗試暴力關(guān)閉"); } }catch(InterruptedExceptionex){ System.out.println("異常了"); Thread.currentThread().interrupt(); } } } } 1234567891011121314151617181920212223242526272829303132333435363738394041
2.在啟動(dòng)類中加入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
這樣我們就配置好了,我們?cè)賮?lái)測(cè)試一遍,test的接口還是休眠10秒
我們發(fā)現(xiàn)這次沒(méi)有報(bào)錯(cuò)了,他是等待了一段時(shí)間之后再結(jié)束的線程池,這個(gè)時(shí)間就是我們?cè)贓legantShutdownConfig類中配置的waitTime。
那可能你會(huì)有疑問(wèn)了,jvm沒(méi)有立即停止,那這個(gè)時(shí)候在有請(qǐng)求會(huì)發(fā)生什么呢?如果關(guān)閉的時(shí)候有新的請(qǐng)求,服務(wù)將不在接收此請(qǐng)求。
數(shù)據(jù)備份操作
如果我想在服務(wù)停止的時(shí)候做點(diǎn)備份操作啥的,應(yīng)該怎么做呢?其實(shí)很簡(jiǎn)單在你要執(zhí)行的方法上添加一個(gè)注解即可:@PreDestroy
“
Destroy:消滅、毀滅 pre:前綴縮寫(xiě)
”
所以合在一起的意思就是在容器停止之前執(zhí)行一次,你可以在這里面做備份操作,也可以做記錄停機(jī)時(shí)間等。
新增服務(wù)停止備份工具類:DataBackupConfig.java
packagecom.ymy.config; importorg.springframework.context.annotation.Configuration; importjavax.annotation.PreDestroy; @Configuration publicclassDataBackupConfig{ @PreDestroy publicvoidbackData(){ System.out.println("正在備份數(shù)據(jù)。。。。。。。。。。。"); } } 123456789101112131415
我們?cè)賮?lái)測(cè)試然后打印控制臺(tái)日志:
審核編輯:湯梓紅
-
Linux
+關(guān)注
關(guān)注
87文章
11292瀏覽量
209322 -
程序
+關(guān)注
關(guān)注
117文章
3785瀏覽量
81001 -
命令
+關(guān)注
關(guān)注
5文章
683瀏覽量
22011 -
python
+關(guān)注
關(guān)注
56文章
4792瀏覽量
84627 -
kill
+關(guān)注
關(guān)注
0文章
9瀏覽量
2104
原文標(biāo)題:為什么技術(shù)牛人都不建議用 kill -9 關(guān)閉程序?
文章出處:【微信號(hào):浩道linux,微信公眾號(hào):浩道linux】歡迎添加關(guān)注!文章轉(zhuǎn)載請(qǐng)注明出處。
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論