본문 바로가기

Spring & Java

Spring mvc async rest api

반응형
/*
결제 내역 조회시 해당 결제 내역에 사용자 정보를 포함해야 한다. 
사용자 정보 조회를 위해 결제아이디로 사용자 정보를 조회 후 결제 정보에 조인 시켜야 한다. 
해당 프로세스를 비동기적으로 처리 하도록 한다.
*/

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();
  }
}
반응형

'Spring & Java' 카테고리의 다른 글

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
LocalDateTime hour step  (0) 2021.10.31