ABOUT ME

포소니는 나의 하루이자 누군가의 공감입니다. 조용히 머물러도 좋고, 가볍게 이야기를 남겨도 좋아요. 당신의 일상도, 이곳에 스며들길 바랍니다.

Today
Yesterday
Total
  • Spring mvc async rest api
    Tech/SpringBoot 2021. 11. 7. 16:54
    반응형
    /*
    결제 내역 조회시 해당 결제 내역에 사용자 정보를 포함해야 한다. 
    사용자 정보 조회를 위해 결제아이디로 사용자 정보를 조회 후 결제 정보에 조인 시켜야 한다. 
    해당 프로세스를 비동기적으로 처리 하도록 한다.
    */

    Enable Async  and config thread pool

    @EnableAsync
    @Configuration
    public class BeanConfig {
    
      /**
       * @see https://kapentaz.github.io/spring/Spring-ThreadPoolTaskExecutor-%EC%84%A4%EC%A0%95/#
       */
      @Bean("accounting-async-thread")
      public Executor asyncThread(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setMaxPoolSize(100);
        threadPoolTaskExecutor.setCorePoolSize(10);
        threadPoolTaskExecutor.setQueueCapacity(10);
        threadPoolTaskExecutor.setThreadNamePrefix("Async-");
        return threadPoolTaskExecutor;
      }
    }

    Create Async method for paymenthistory

    @Service
    public class AsyncPaymentService {
    
      @Async("accounting-async-thread")
      public CompletableFuture asyncPaymentHistory() {
        return new AsyncResult<>(getAccountingList()).completable();
      }
    
      public List getAccountingList() {
        //external api call for accounting list
        //join accounting + userInfo
        return Arrays.asList();
      }
    
      public UserInfoDto getUserInfo(String userId) {
        //external api call for userInfo
        return UserInfoDto.builder().build();
      }
    }

    Async API Controller

    @RestController
    @RequestMapping("/api/payment")
    public class AsyncRestController {
    
      private final AsyncPaymentService asyncPaymentService;
    
      public AsyncRestController(AsyncPaymentService asyncPaymentService) {
        this.asyncPaymentService = asyncPaymentService;
      }
    
      @GetMapping("/history")
      public CompletableFuture history(){
        return asyncPaymentService.asyncPaymentHistory();
      }
    }
    반응형

    'Tech > SpringBoot' 카테고리의 다른 글

    Java Conditional Unit Test  (0) 2022.05.21
    spring aop  (0) 2021.11.07
    Spring mvc async rest api  (0) 2021.11.07
    java excell downloader in spring boot  (0) 2021.10.31
    Java conver t JsonArray to List  (0) 2021.10.31
Designed by Tistory.