개요
개인 프로젝트를 진행하면서 더미 데이터가 필요하여 더미 데이터를 넣어주는 코드를 작성하고 컴파일을 진행하였지만 오류는 나오지 않고 서버 연결이 되지 않는 상황이 발생하였다.
코드
@Component
public class DummyData {
@Autowired
private UserRepository repository;
@Autowired
private UserUtil userUtil;
@PostConstruct
public void init() {
List<UserEntity> lists = new ArrayList<UserEntity>();
for (int i = 0; i < 10000; i++) {
lists.add(new UserEntity("username" + i, userUtil.passwordEncoding("1234" + i)));
}
repository.saveAll(lists);
}
}
정상적인 상황:

현 상황

원인
만개의 더미 데이터를 넣으려고 해서 생긴 문제였다. 한 번에 10000개는 못 넣는 것인지 테스트를 진행해봤다.
List<UserEntity> lists = new ArrayList<UserEntity>();
for (int i = 0; i < 10000; i++) {
lists.add(new UserEntity("username" + i, userUtil.passwordEncoding("1234" + i)));
}
repository.saveAll(lists);
테스트 케이스 1) 10개


정상적으로 동작하는 모습이다.
테스트 케이스 2) 100개

정상적으로 작동했다 하지만 서버가 동작하는 데 걸리는 시간이 2배 넘게 걸렸다.
테스트 케이스 3) 1000개

정상적으로 작동했다 하지만 서버가 동작하는 데 걸리는 시간이 2배 넘게 걸렸다.
결과
1000개의 경우도 마찬가지로 정상적으로 동작했지만 이번에는 7배의 시간이 걸렸다. 생각해봤을 때 서버 동작이 멈춘 게 아니라 많은 데이터를 저장하려다 보니 서버 가동이 늦춰진 것으로 생각된다.
해결 방안
서버 컴파일이 끝난 후 데이터를 집어넣어야 된다고 판단했다.
해결 방안 1) ApplicationListener<ContextRefreshedEvent>
@Service
public class DummyData implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private UserRepository repository;
@Autowired
private UserUtil userUtil;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// TODO Auto-generated method stub
List<UserEntity> lists = new ArrayList<UserEntity>();
for (int i = 0; i < 1000; i++) {
lists.add(new UserEntity("username" + i, userUtil.passwordEncoding("1234" + i)));
}
repository.saveAll(lists);
System.out.println("init() ");
}
}
해결 방안 2) ApplicationRunner
@Component
public class DummyData implements ApplicationRunner {
// implements ApplicationListener<ContextRefreshedEvent>
@Autowired
private UserRepository repository;
@Autowired
private UserUtil userUtil;
@Override
public void run(ApplicationArguments args) throws Exception {
// TODO Auto-generated method stub
System.out.println("init() ");
List<UserEntity> lists = new ArrayList<UserEntity>();
for (int i = 0; i < 1000; i++) {
lists.add(new UserEntity("username" + i, userUtil.passwordEncoding("1234" + i)));
}
repository.saveAll(lists);
}
}
결론
기타 여러 가지 방법이 있다.. @EventListner도 사용해도 된다. 컴퍼넌트 스캔 시점에 데이터를 넣는 것은 서버 시작을 늦추는 것이라고 생각하여 데이터를 넣는 것은 서버가 정상적으로 시작되고 난 후가 안전하다고 생각한다.
'문제해결 및 코드 만들기' 카테고리의 다른 글
| [문제해결] AWS 스프링 빌드 중 발생한 문제점 (0) | 2022.05.13 |
|---|---|
| [문제해결] 회원 가입 시 동시성 문제가 발생하는가 (0) | 2022.05.11 |
| 스프링 MultipartFile을 사용할 때 나타난 오류들 (0) | 2022.05.02 |
| Spring AOP을 활용한 문제해결 - JWT 토큰 유저 검증 (0) | 2022.04.28 |
| 2022-01-20(개인 프로젝트) 시간 단축 (0) | 2022.01.20 |