ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Spring @Async 사용하기
    카테고리 없음 2020. 6. 25. 12:42

    1. 개요

    Spring비동기 실행 지원 과 @Async 주석을 살펴볼 것이다 .

    간단히 말해서 빈 메서드에 주석 @Async을 만들 것입니다 별도의 스레드에서 실행 호출 메서드의 완료를 기다리지 않습니다. 발신자 즉.

    Spring의 흥미로운 측면 중 하나는 프레임 워크의 이벤트 지원 이 해당 경로로 가고 싶다면 비동기 처리를 지원 한다는 것입니다.

    2. 비동기 지원 활성화

    간단하게 @EnableAsync를 추가

    @Configuration
    @EnableAsync
    public class SpringAsyncConfig { ... }

    활성화 주석만으로 충분하지만 예상대로 구성을 위한 몇 가지 간단한 옵션도 있습니다.

    • annotation – @EnableAsync @Async javax.ejb.Asynchronous

      기본적으로

      는 Spring의

      주석과 EJB 3.1을감지합니다.

      ; 이 옵션을 사용하면 다른 사용자 정의 주석 유형도 감지 할 수 있습니다

    • mode 조언

      –사용해야하는

      유형을 나타냅니다– JDK 프록시 기반 또는 AspectJ 직조

    • proxyTargetClass 프록시 모드

      –사용해야하는

      유형– CGLIB 또는 JDK; 이 속성은

      가 AdviceMode.PROXY 로 설정된경우에만 적용됩니다.

    • order AsyncAnnotationBeanPostProcessor

      가 적용되는 순서를 설정합니다. 기본적으로 마지막으로 실행되므로 기존의 모든 프록시를 고려할 수 있습니다

    작업 네임 스페이스 를 사용하여 XML 구성을 사용하여 비동기 처리를 활성화 할 수도 있습니다 .

    <task:executor id="myexecutor" pool-size="5"  />
    <task:annotation-driven executor="myexecutor"/>

    3. @Async 주석

    먼저 – 규칙을 살펴 보자 – @Async 에는 두 가지 제한이 있습니다.

    • 공용

      메소드에만 적용해야합니다.

    • 동일한 클래스 내에서 비동기 메소드를 호출하는 자체 호출이 작동하지 않습니다.

    그 이유는 간단 합니다.이 방법은 공개 될 수 있도록 공개 되어야합니다. 그리고 자체 호출은 프록시를 무시하고 기본 메소드를 직접 호출하기 때문에 작동하지 않습니다 .

    3.1. void 반환 유형의 방법

    다음은 void 반환 유형으로 메소드를 비동기식으로 실행하도록 구성하는 간단한 방법입니다.

    @Async
    public void asyncMethodWithVoidReturnType() {
        System.out.println("Execute method asynchronously. "
          + Thread.currentThread().getName());
    }

    3.2. 리턴 타입의 메소드

    @Async 는 미래의 실제 수익을 줄임 으로써 리턴 유형의 메소드에도 적용될 수 있습니다.

    @Async
    public Future<String> asyncMethodWithReturnType() {
        System.out.println("Execute method asynchronously - "
          + Thread.currentThread().getName());
        try {
            Thread.sleep(5000);
            return new AsyncResult<String>("hello world !!!!");
        } catch (InterruptedException e) {
            //
        }
    
        return null;
    }

    Spring은 또한 Future 를 구현 하는 AsyncResult 클래스를 제공합니다 . 비동기 메소드 실행 결과를 추적하는 데 사용할 수 있습니다.

    이제 위의 메소드를 호출하고 Future 객체를 사용하여 비동기 프로세스의 결과를 검색하자 .

    public void testAsyncAnnotationForMethodsWithReturnType()
      throws InterruptedException, ExecutionException {
        System.out.println("Invoking an asynchronous method. "
          + Thread.currentThread().getName());
        Future<String> future = asyncAnnotationExample.asyncMethodWithReturnType();
    
        while (true) {
            if (future.isDone()) {
                System.out.println("Result from asynchronous process - " + future.get());
                break;
            }
            System.out.println("Continue doing something else. ");
            Thread.sleep(1000);
        }
    }

    4. Exceutor

    기본적으로 Spring은 SimpleAsyncTaskExecutor 를 사용 하여 실제로 이러한 메소드를 비동기 적으로 실행합니다. 기본값은 응용 프로그램 수준 또는 개별 방법 수준에서 두 가지 수준으로 재정의 할 수 있습니다.

    4.1. 메소드 레벨에서 exceutor override

    필수 실행 프로그램은 구성 클래스에서 선언해야합니다.

    @Configuration
    @EnableAsync
    public class SpringAsyncConfig {
    
        @Bean(name = "threadPoolTaskExecutor")
        public Executor threadPoolTaskExecutor() {
            return new ThreadPoolTaskExecutor();
        }
    }

    그런 다음 실행기 이름을 @Async 의 속성으로 제공해야합니다.

    @Async("threadPoolTaskExecutor")
    public void asyncMethodWithConfiguredExecutor() {
        System.out.println("Execute method with configured executor - "
          + Thread.currentThread().getName());
    }

    4.2. 응용 프로그램 수준에서 실행자를 재정의

    구성 클래스는 AsyncConfigurer 인터페이스를 구현해야합니다. 즉 , getAsyncExecutor () 메소드를 구현해야합니다 . 여기에서 전체 애플리케이션에 대한 실행기를 반환 할 것입니다. 이제 @Async로 주석이 달린 메소드를 실행하는 기본 실행기가됩니다 .

    @Configuration
    @EnableAsync
    public class SpringAsyncConfig implements AsyncConfigurer {
    
        @Override
        public Executor getAsyncExecutor() {
            return new ThreadPoolTaskExecutor();
        }
    
    }

    5. 예외 처리

    메소드 리턴 유형이 Future 인 경우 예외 처리가 용이합니다. Future.get () 메소드는 예외를 처리 합니다.

    그러나 반환 유형이 void 이면 예외가 호출 스레드로 전파되지 않습니다 . 따라서 예외를 처리하기 위해 추가 구성을 추가해야합니다.

    AsyncUncaughtExceptionHandler 인터페이스 를 구현하여 사용자 정의 비동기 예외 핸들러를 작성합니다 . handleUncaughtException () catch되지 않은 비동기 예외가있을 때 메서드가 호출됩니다 :

    public class CustomAsyncExceptionHandler
      implements AsyncUncaughtExceptionHandler {
    
        @Override
        public void handleUncaughtException(
          Throwable throwable, Method method, Object... obj) {
    
            System.out.println("Exception message - " + throwable.getMessage());
            System.out.println("Method name - " + method.getName());
            for (Object param : obj) {
                System.out.println("Parameter value - " + param);
            }
        }
    
    }

    이전 섹션에서는 구성 클래스로 구현 된 AsyncConfigurer 인터페이스를 살펴 보았습니다 . 이 과정에서 getAsyncUncaughtExceptionHandler () 메서드를 재정 의하여 사용자 지정 비동기 예외 처리기를 반환해야합니다.

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new CustomAsyncExceptionHandler();
    }

    6. 결론

    이 튜토리얼에서는 Spring으로 비동기 코드실행하는 방법 을 살펴 보았습니다 . 우리는 기본 구성 및 주석으로 시작하여 작동하게 만들었지 만 자체 실행기 제공 또는 예외 처리 전략과 같은 고급 구성도 살펴 보았습니다.

    출처: https://www.baeldung.com/spring-async

    댓글

Designed by Tistory.