최근에 요구 사항이 발생했는데, 이는 서버가 요청을받을 때 결과를 반환하기 전에 작업 실행을 완료 할 필요가 없다는 것입니다. 결과를 즉시 반환하고 작업이 비동기 적으로 실행되도록 할 수 있습니다. 가장 먼저 고려해야 할 것은 작업을 실행하거나 실행을 위해 작업을 스레드 풀에 제출하기 위해 새 스레드를 시작하는 것입니다. 두 방법 모두 괜찮습니다. 그러나 봄은 너무 강력하여 더 간단한 방법이 있어야합니다. 나는 단지 그것을 검색했고 그것은 실제로 그것을 가지고있다. 두 개의 주석 @enableAsync와 @async를 사용하면 괜찮습니다.
메소드에 @async 주석을 추가하십시오
packing me.deweixu.aysncdemo.service; public Interface Asyncservice {void asyncmethod (String arg);} Me.deweixu.aysncdemo.service.ipml; import me.deweixu.aysncdemo.service.asyncservice; import org.springframework.scheduling.annotation.async; import org.springframework.stereotype.service.serviceplic asyncservice implestempl implestement priments Asyncservice {@async @override public void asyncmethod (String arg) {system.out.println ( "arg :" + arg); System.out.println ( "=====" + Thread.currentThread (). getName () + "==================);}} @EnableAsync
시작 클래스 또는 구성 클래스에 @enableAsync 주석을 추가하십시오.
Me.deweixu.aysncdemo; import org.springframework.springApplication; import org.springframework.boot.autoconfigure.springbootApplication; import org.springframework.scheduling.annotation.enbleasync; springsonplication pollich@springopplication aysncdemoapplication {public static void main (String [] args) {springApplication.run (aysncdemoapplication.class, args); }} 시험
Me.deweixu.aysncdemo; import me.deweixu.aysncdemo.service.asyncservice; import org.junit.test; import org.junit.runner.runwith; import org.spramework.beans.beans.annotation.autowired; import org.springframework.boot.test.context.springboottest; import org.springframework.test.context.junit4.springrunner; @runwith (springrunner.class) @springboottestpublic class aysncdemoaptiontests {afealwired asyncservice asyncservice; @test public void testasync () {system.out.println ( "======" + thread.currentThread (). getName () + "=======================);=================
2018-03-25 21 : 30 : 31.391 정보 28742 --- [Main] .SaannotationAsyncexecutioninterceptor : 비동기 처리를 위해 발견 된 작업 집행 Bean 없음 : Taskexecutor 유형의 콩 없음 'Taskexecutor'라는 콩이 없습니다.
arg : 비동기
===== SMEPLEASYNCTASKEXECUTOR-1 ============
위의 결과에서 Asyncservice.asyncmethod ( "Async")는 실제로 비동기 적으로 실행되며 새 스레드를 사용합니다.
집행자를 지정하십시오
위의 실행 로그에서 Spring은 SimpleAsyncTaskexEcutor를 사용하여 기본적으로 작업을 비동기 적으로 실행한다고 추측 할 수 있습니다. 이 수업을 검색 할 수 있습니다. @async는 또한 사용자 정의 집행자를 지정할 수 있습니다.
스타트 업 클래스에 사용자 정의 집행자를 추가하십시오
Me.deweixu.aysncdemo; import org.springframework.springApplication; import org.springframework.boot.autoconfigure.springbootApplication; import org.springframework.context.annotation.bean org org.springframework.scheduling org.springframework.scheduling.concurrent.threadpooltaskexecutor; import java.util.concurrent.executor;@enableasync@springbootapplicationpublic class aysncdemoapplication {public static void main (strings) {springapplication.run, aysncapplication. args); } @Bean (이름 = "ThreadPoolTasKexEcutor") 공개 집행자 ThreadPoolTasKexEcutor () {return new ThreadPooltasKexEcutor (); }}집행자를 지정하십시오
Me.deweixu.aysncdemo.service.ipml; import me.deweixu.aysncdemo.service.asyncservice; import org.springframework.scheduling.annotation.async; import org.springframework.stereotype.service.serviceplic asyncservice implestempl implestement priments AsyncService {@async ( "ThreadPooltasKexEcutor") @Override public void AsyncMethod (String Arg) {System.out.println ( "arg :" + arg); System.out.println ( "=====" + Thread.currentThread (). getName () + "======================);}}이런 식으로 작업을 비동기로 실행할 때 ThreadPooltasKexecutor를 사용하십시오
기본 집행자를 설정하십시오
위에서 언급 한 바와 같이, @async가 집행자를 지정하지 않으면 단순한 기본적으로 SimpleAsynctaskexecutor가 사용됩니다. 실제로, 기본 임원은 AsyncConfigurer 인터페이스를 사용하여 구성 할 수 있습니다.
@ConfigurationPublic 클래스 SpringAsyncConfig는 AsyncConfigurer {@override public executor getAsyncexecutor () {return new ThreadPoolTaskexEcutor (); }} 예외 캡처
비동기 실행 방법에서 예외가 발생할 수 있습니다. 작업 내부의 시도 캐치를 사용하여 예외를 처리 할 수 있습니다. 작업이 예외를 던지면 Spring은 또한 잡을 수있는 방법을 제공합니다.
Asyncuncuggexception Handler 인터페이스를 구현하십시오
공개 클래스 CustomAsyNcexceptionHandler는 Asyncuncuggexception Handler를 구현합니다. {@override public void handsunctexception (Throwable Throwable, 메소드 메소드, Object ... obj) {system.out.println ( "예외 메시지 -" + strashable.getmessage ()); System.out.println ( "메소드 이름 -" + method.getName ()); for (object param : obj) {system.out.println ( "매개 변수 값 -" + param); }}}asyncconfigurer 인터페이스 다시 작성 getAsyncuncuggexception Handler 메소드를 구현하십시오
@ConfigurationPublic 클래스 SpringAsyncConfig는 AsyncConfigurer {@override public executor getAsyncexecutor () {return new ThreadPoolTaskexEcutor (); } @override public asyncuncuggexceptionHandler getAsyncuncuggexceptionHandler () {return new CustomAsyNcexceptionHandler (); }}AsyncMethod 메소드를 다시 작성하여 예외를 던지십시오.
@async @override public void asyncmethod (String arg) {system.out.println ( "arg :" + arg); System.out.println ( "=====" + Thread.currentThread (). getName () + "======================);실행 결과 :
=================
arg : 비동기
===== ThreadPooltaskexecutor-1 ===========
예외 메시지 -Async NullPointerException
메소드 이름 -AsyncMethod
매개 변수 값 - 비동기
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.