Prematurely reached end of stream 에러 해결

KimJinkYU·2022년 10월 17일
2

개발 기록

목록 보기
7/8

올해 6월 초쯤 간헐적으로 발생하던 에러 해결 기록입니다.

🕷에러 발생

스프링 프레임워크에서 간헐적으로 Mongo DB에서 연결이 잘 되지 않아 org.springframework.data.mongodb.UncategorizedMongoDbException: Prematurely reached end of stream 에러가 발생

📚찾아본 문서

MongoDB ATLAS + Spring 붙이기
StackOverFlow -
MongoSocketReadException: Prematurely reached end of stream (after a period of inactivity)

Exception resolution of MongoDB Prematurely reached end of stream in spring boot

  • 처음에 찾은 방법 → keep-alive: true, timeout 시간 설정 → 현재 사용하는 3.6 버전에서는 keep-alive: true가 기본값으로 설정

  • 다음으로 찾은 방법 maxConnectionIdleTime 설정
    -> 해당 방법을 통해 해결

  • 추후 시도해볼 예정이었던 방법 ssl = true 로 설정

✏️해결 방법

→ maxConnectionIdleTime 10초로 설정

MongoClientSettings에 applyToConnectionPoolSettings 설정을 추가하는 법을 몰라서 공식 문서 참고
→ Block으로 되어있어서 당황했는데 그냥 함수 인터페이스로 생각됨, Lambda 함수를 추가해서 설정

📖예시 코드

private MongoClientSettings createMongoClientSettings(MongoProperties mongoProperties){
    ConnectionString ConnectionString = new ConnectionString(mongoProperties.getUri());
    return MongoClientSettings.builder()
        .readConcern(ReadConcern.DEFAULT)
        .writeConcern(WriteConcern.MAJORITY)
        .readPreference(ReadPreference.primary())
        .applyToConnectionPoolSettings(builder -> builder.maxConnectionIdleTime(10L, TimeUnit.SECONDS))
        .applyConnectionString(ConnectionString)
        .build();
}

추가된 코드 (maxConnectionIdleTime 10초로 설정)

.applyToConnectionPoolSettings(builder -> builder.maxConnectionIdleTime(10L, TimeUnit.SECONDS))

profile
I'll do my best

0개의 댓글