Repository navigation
✨ [Feat] 웹소켓 재연결 로직 추가 #139
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
88 changes: 84 additions & 4 deletions
88
src/main/java/com/example/scoi/domain/websocket/WebsocketConnect.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,27 +1,107 @@ | ||
| package com.example.scoi.domain.websocket; | ||
|
|
||
| import com.example.scoi.domain.websocket.code.WebsocketErrorCode; | ||
| import com.example.scoi.domain.websocket.event.WebsocketConnectionEvent.ConnectedEvent; | ||
| import com.example.scoi.domain.websocket.event.WebsocketConnectionEvent.DisconnectedEvent; | ||
| import com.example.scoi.domain.websocket.exception.WebsocketException; | ||
| import com.example.scoi.domain.websocket.handler.UpbitTickerHandler; | ||
| import jakarta.annotation.PreDestroy; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.beans.factory.ObjectProvider; | ||
| import org.springframework.boot.context.event.ApplicationReadyEvent; | ||
| import org.springframework.context.event.EventListener; | ||
| import org.springframework.retry.annotation.Backoff; | ||
| import org.springframework.retry.annotation.Recover; | ||
| import org.springframework.retry.annotation.Retryable; | ||
| import org.springframework.scheduling.annotation.Async; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.web.socket.client.WebSocketClient; | ||
|
|
||
| import java.util.concurrent.Executors; | ||
| import java.util.concurrent.ScheduledExecutorService; | ||
| import java.util.concurrent.ScheduledFuture; | ||
| import java.util.concurrent.TimeUnit; | ||
|
|
||
| @Service | ||
| @RequiredArgsConstructor | ||
| @Slf4j | ||
| public class WebsocketConnect { | ||
|
|
||
| private final WebSocketClient webSocketClient; | ||
| private final UpbitTickerHandler upbitTickerHandler; | ||
| private final ObjectProvider<WebsocketConnect> selfProvider; // AOP 우회 방지를 위한 프록시 의존성 | ||
|
|
||
| private static final String PUBLIC_URL = "wss://api.upbit.com/websocket/v1"; | ||
|
|
||
| // 실시간 가격 변동 체크 | ||
| // 워치독(Half-Open 헬스체크) 전용 스케줄러 | ||
| private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); | ||
| private ScheduledFuture<?> watchdogTask; | ||
|
|
||
| @EventListener(ApplicationReadyEvent.class) | ||
| public void connect(){ | ||
| log.info("[ Websocket ]: 디페깅 알고리즘 구동 시작..."); | ||
| webSocketClient.execute(upbitTickerHandler, PUBLIC_URL); | ||
| public void init() { | ||
| log.info("[ Websocket ]: 애플리케이션 준비 완료."); | ||
| selfProvider.getObject().connectWithRetry(); | ||
| } | ||
|
|
||
| @Async | ||
| @Retryable( | ||
| retryFor = WebsocketException.class, | ||
| maxAttempts = 10, | ||
| backoff = @Backoff(delay = 1000, multiplier = 2, maxDelay = 60000) | ||
| ) | ||
| public void connectWithRetry() { | ||
| log.info("[ Websocket ]: 업비트 웹소켓 연결 시도 중... URL: {}", PUBLIC_URL); | ||
| try { | ||
| // execute()의 리턴값인 Future를 대기(get)하여 타임아웃이나 연결 거부 시 예외를 발생시키도록 유도 | ||
| webSocketClient.execute(upbitTickerHandler, PUBLIC_URL).get(5, TimeUnit.SECONDS); | ||
| } catch (Exception e) { | ||
| log.error("[ Websocket ]: 웹소켓 연결 실패: {}", e.getMessage()); | ||
| // 예외를 던져서 @Retryable이 AOP 기반 백오프 및 재시도를 수행하도록 트리거 | ||
| throw new WebsocketException(WebsocketErrorCode.UPBIT_WEBSOCKET_ERROR); | ||
| } | ||
| } | ||
|
|
||
| @Recover | ||
| public void recover(Exception e) { | ||
| log.error("[ Websocket ]: 웹소켓 재연결 최대 시도 횟수(10회) 초과"); | ||
|
|
||
| // 2시간뒤 다시 시도 | ||
| scheduler.schedule(() -> { | ||
| log.info("[ Websocket ]: 시스템 복구를 위해 웹소켓 재연결 사이클을 다시 시작합니다."); | ||
| selfProvider.getObject().connectWithRetry(); | ||
| }, 2, TimeUnit.HOURS); | ||
| } | ||
|
|
||
| @EventListener | ||
| public void onConnected(ConnectedEvent event) { | ||
| log.info("[ Websocket ]: 이벤트 수신 - 웹소켓 연결 활성화 완료."); | ||
|
|
||
| if (watchdogTask != null && !watchdogTask.isCancelled()) { | ||
| watchdogTask.cancel(false); | ||
| } | ||
| // 10초마다 마지막 수신 시간 검사 | ||
| watchdogTask = scheduler.scheduleAtFixedRate(() -> { | ||
| long idleTime = System.currentTimeMillis() - upbitTickerHandler.getLastMessageTime(); | ||
| if (idleTime > 30_000) { // 30초 초과 시 | ||
| log.error("[ Websocket ]: 30초간 업비트 응답이 없습니다..."); | ||
| upbitTickerHandler.closeSession(); // DisconnectedEvent 유발 | ||
| } | ||
| }, 10, 10, TimeUnit.SECONDS); | ||
| } | ||
|
|
||
| @EventListener | ||
| public void onDisconnected(DisconnectedEvent event) { | ||
| log.warn("[ Websocket ]: 이벤트 수신 - 웹소켓 연결 해제. 재연결 시도"); | ||
| if (watchdogTask != null) { | ||
| watchdogTask.cancel(false); | ||
| } | ||
| selfProvider.getObject().connectWithRetry(); | ||
| } | ||
|
|
||
| @PreDestroy | ||
| public void shutdown() { | ||
| log.info("[ Websocket ]: 워치독 스케줄러 종료 중..."); | ||
| scheduler.shutdown(); | ||
| } | ||
| } | ||
20 changes: 20 additions & 0 deletions
20
src/main/java/com/example/scoi/domain/websocket/code/WebsocketErrorCode.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| package com.example.scoi.domain.websocket.code; | ||
|
|
||
| import com.example.scoi.global.apiPayload.code.BaseErrorCode; | ||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| public enum WebsocketErrorCode implements BaseErrorCode { | ||
|
|
||
| UPBIT_WEBSOCKET_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, | ||
| "WEBSOCKET500_1", | ||
| "웹소켓 연결 도중 에러가 발생했습니다."), | ||
| ; | ||
|
|
||
| private final HttpStatus status; | ||
| private final String code; | ||
| private final String message; | ||
| } |
6 changes: 6 additions & 0 deletions
6
src/main/java/com/example/scoi/domain/websocket/event/WebsocketConnectionEvent.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| package com.example.scoi.domain.websocket.event; | ||
|
|
||
| public interface WebsocketConnectionEvent { | ||
| record ConnectedEvent() implements WebsocketConnectionEvent {} | ||
| record DisconnectedEvent() implements WebsocketConnectionEvent {} | ||
| } |
10 changes: 10 additions & 0 deletions
10
src/main/java/com/example/scoi/domain/websocket/exception/WebsocketException.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| package com.example.scoi.domain.websocket.exception; | ||
|
|
||
| import com.example.scoi.global.apiPayload.code.BaseErrorCode; | ||
| import com.example.scoi.global.apiPayload.exception.ScoiException; | ||
|
|
||
| public class WebsocketException extends ScoiException { | ||
| public WebsocketException(BaseErrorCode code) { | ||
| super(code); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.