스프링 MVC3.2 이상에서, 요청의 비동기식 처리가 추가되며, 이는 Servlet3에 기초하여 캡슐화된다.
1. Web.xml을 수정합니다
<? xml version = "1.0"encoding = "utf-8"?> <web-app version = "3.0"xmlns = "http://java.sun.com/xml/xml/ns/javaee"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance. xsi : schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> ... </web-app>
1.1. Declare version = "3.0", deplare web-app_3_0.xsd
1.2. 서블릿 또는 필터 설정에 대한 비동기 지원 활성화 : <Async-Supported> true </async-supported> 웹 애플리케이션의 web.xml을 수정하려면
<!- 스프링 MVC -> <servlet> <servlet-name> springmvc </servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherServlet </servlet-class> <init-param> <param-name> cont ExtConfiglocation </param-name> <param- value> ... </param-value> </init-param> <load-on-startup> 1 </load-on-startup> <Async-supported> true </async-supported> </servlet>
2. 컨트롤러 클래스를 지원합니다
2.1. 비동기 처리를 완료하기 위해 java.util.concurrent.callable을 반환합니다
패키지 org.springframework.samples.mvc.async; java.util.concurrent.callable import; org.springframework.stereotyp.controller import; import org.springframework.ui.model; org.springframework.web.bind.annotation.exceptionhandler import; org.springframework.web.bind.annotation.requestmapping; org.springframework.web.bind.annotation.requestparam; import org.springframework.web.bind.annotation.responsebody; import org.springframework.web.context.request.async.webasynctask; @controller @requestmapping ( "/async/callable") public class callableController {@requestmapping ( "/respons-body") public @response body callable <string> callable () {return new Callable <string> () {@override public string call () 예외 {thread.sleep (2000); "호출 가능한 결과"를 반환합니다. }}}; } @requestmapping ( "/view") public callable <string> callablewithView (최종 모델 모델) {return new callable <string> () {@override public string () rows exception {thread.sleep (2000); model.addattribute ( "foo", "bar"); model.addattribute ( "과일", "사과"); "views/html"을 반환합니다. }}; } @RequestMapping ( "/Exception") public @ResponseBody Callable Callable CallableWithException (final @RequestParam (필수 = False, DefaultValue = "True") 부울 처리) {return new Callable <string> () {@override public string call () 예외 {stride.sleep (2000); if (handled) {// 아래의 handleException 메소드를 참조하십시오. } else {새로운 불법 불법 행정 exception ( "호출 가능한 오류"); }}}}}; } @RequestMapping ( "/custom-timeout-handling") public @ResponseBody WebAsyncTask <string> callablewithCustOmtable = new Callable = new Callable <string> () {@override public string () exception {Thread.Sleep (2000); "호출 가능한 결과"를 반환합니다. }}; 새로운 webasynctask <string> (1000, 호출 가능)을 반환합니다. } @ExceptionHandler @ResponseBody public String handleException (ElegalStateException ex) {return "handled exception :" + ex.getMessage (); }}2.2. RETORG.SpringFramework.web.context.request.async.deferredresult JMS 또는 AMQP 메시지, Redis 알림 등과 같은 비동기 처리가 완료되면 :
@requestmapping ( "/quotes")@responseBodyPublic DeferredResult <string> quotes () {deferredresult <string> deferredresult = new Deferredresult <string> (); // 대기열 또는지도에 DeferRedResult를 추가 ... DEFERREDRESULT를 반환합니다.3. 스프링 구성 파일 수정
Spring MVC DTD의 선언은 3.2보다 크거나 동일해야합니다.
<mvc : 주석 구동> <!-기본 시간 초과-> <mvc : async-support default-timeout = "3000"/> </mvc : 주석 구동>을 사용할 수 있습니다
실제 사용 예 :
function Deferred () {$ .get ( 'Quotes.htm', function (data) {console.log (data); jeferred (); // 요청이 완료 될 때마다 다른 요청을 보내서 정기적으로 새로 고침을 피하기 위해 클라이언트가 새로 고침을 피하기 위해 데이터를 얻으려면 데이터를 얻습니다});}); 이를 수행하는 장점은 웹 서버 연결 풀의 장기 사용을 피하여 성능 문제를 일으 킵니다. 호출 후 비 WEB 서비스 스레드가 생성되어 처리하여 웹 서버의 처리량을 증가시킵니다 ~~
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.