Sangil's blog

https://github.com/ChoiSangIl Admin

spring 3.x @Async (비동기) 설정방법 DEV / WEB

2021-05-06 posted by sang12


1. 사용법

- @EnableAsync 어노테이션 추가(안하면 비동기 호출이 안먹힘)

@Service("service")
@EnableAsync 
public class ServieImpl implements Service {
}

- @Async 어노테이션 추가 및 서비스 구현체 함수 생성

@Service("service")
@EnableAsync 
public class ServieImpl implements Service {
@Async
public void asyncTest() {
try {
Thread.sleep(5000);
System.out.println("####################" + Thread.currentThread().getId());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

-Controller 에서 비동기 함수 호출

@Controller("restful")
public class Restful{
@RequestMapping("/asyncTest")
public @ResponseBody void asyncTest(final @RequestBody Map<String, Object> parameterMap) {
TransferObject transferObject = new TransferObject();

try {
System.out.println("@@@@@@@@@@@@@@@@@@@@@@"+Thread.currentThread().getId());
SettlementService.asyncTest();
System.out.println("!!!!!!!!!!!!!!!!!!!!!!");
} catch (RuntimeException e) {

}
}
}

-출력 결과 

@@@@@@@@@@@@@@@@@@@@@@44
!!!!!!!!!!!!!!!!!!!!!!
####################45

-> Thread id가 다른걸 확인할 수 있다.

REPLY