-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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,7 @@ | ||
### emitter 연결(조회) | ||
GET {{host}}/test/event-stream | ||
Authorization: {{authorization}} | ||
|
||
### 알림 전송 | ||
POST {{host}}/notification?message=hello~5 | ||
Authorization: {{authorization}} |
49 changes: 49 additions & 0 deletions
49
api/src/main/kotlin/com/mashup/dojo/NotificationSseController.kt
This file contains 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,49 @@ | ||
package com.mashup.dojo | ||
|
||
import io.github.oshai.kotlinlogging.KotlinLogging | ||
import org.springframework.web.bind.annotation.GetMapping | ||
import org.springframework.web.bind.annotation.PostMapping | ||
import org.springframework.web.bind.annotation.RestController | ||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter | ||
import java.util.concurrent.CopyOnWriteArrayList | ||
|
||
@RestController | ||
class NotificationSseController { | ||
private val emitters = CopyOnWriteArrayList<SseEmitter>() | ||
private val logger = KotlinLogging.logger { } | ||
|
||
private fun addEmitter(emitter: SseEmitter) { | ||
emitters.add(emitter) | ||
emitter.onCompletion { | ||
logger.debug { "emitter completed successfully" } | ||
emitters.remove(emitter) | ||
} | ||
emitter.onError { | ||
logger.debug { "emitter error occurred: $it" } | ||
emitters.remove(emitter) | ||
} | ||
emitter.onTimeout { | ||
logger.debug { "emitter timed out" } | ||
emitters.remove(emitter) | ||
} | ||
} | ||
|
||
@PostMapping("/notification") | ||
fun send(message: String) { | ||
emitters.forEach { | ||
kotlin.runCatching { | ||
it.send(SseEmitter.event().name("notification-test").data(message)) | ||
}.onFailure { | ||
logger.error { "error occurred: $it" } | ||
} | ||
} | ||
} | ||
|
||
@GetMapping("/test/event-stream") | ||
fun test(): SseEmitter { | ||
// timeout 동안 아무런 데이터 전송되지 않으면 연결 자동 종료 | ||
val emitter = SseEmitter(180000L) | ||
addEmitter(emitter) | ||
return emitter | ||
} | ||
} |