8 Mayıs 2019 Çarşamba

SpringAsync AsyncConfigurerSupport Sınıfı

Giriş
Global olarak kullanılan Executor nesnesini yaratır. Açıklaması şöyle.
this now becomes the default executor to run methods annotated with @Async
Açıklaması şöyle. Yani bu sınıf yerine AsyncConfigurer arayüzünden de kalıtılabilir.
AsyncConfigurer is an Interface provided by Spring, It provides two methods One is if you want to override the TaskExecutor(Threadpool), another is an Exception handler where you can inject your exception handler so it can catch the uncaught exceptions. You can create your own class and implement that one directly. but I will not do that, as an alternative, I will use Spring  AsyncConfigurerSupport class which is annotated by @Configuration and @EnableAsync, and provides a default implementation.
getAsyncExecutor metodu
ThreadPoolTaskExecutor nesnesi döndürür

getAsyncUncaughtExceptionHandler metodu
@Async olarak işaretli metodlardan fırlatılan exception'ları işleyen AsyncUncaughtExceptionHandler  arayüzündne kalıtan nesneyi döndürür.

Örnek
Şöyle yaparız. Burada @Configuration kullanılmış ama bence gerek yok
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class AsynConfiguration extends AsyncConfigurerSupport {
   @Override
   public Executor getAsyncExecutor() {
      ThreadPoolTaskExecutor executor = new 
                ThreadPoolTaskExecutor();
      executor.setCorePoolSize(3);
      executor.setMaxPoolSize(4);
      executor.setThreadNamePrefix("asyn-task-thread-");
      executor.setWaitForTasksToCompleteOnShutdown(true);
      executor.initialize();
      return executor;
  }
  @Override
  public AsyncUncaughtExceptionHandler  
         getAsyncUncaughtExceptionHandler() {
     return new AsyncUncaughtExceptionHandler() {
   
        @Override
        public void handleUncaughtException(Throwable ex, 
           Method method, Object... params) {
           System.out.println("Exception: " + ex.getMessage());
           System.out.println("Method Name: " + method.getName());
           ex.printStackTrace();
        }
    };
  }
}

Hiç yorum yok:

Yorum Gönder