Skip to content

Commit

Permalink
temp; sse-tutorial 코드를 작성해요
Browse files Browse the repository at this point in the history
  • Loading branch information
yaeoni committed Aug 12, 2024
1 parent d7ac6af commit d777565
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
7 changes: 7 additions & 0 deletions _endpoint_test/notification-sse.http
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 api/src/main/kotlin/com/mashup/dojo/NotificationSseController.kt
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
}
}

0 comments on commit d777565

Please sign in to comment.