Skip to content

Instantly share code, notes, and snippets.

@dvas0004
Last active Jul 9, 2018
Embed
What would you like to do?
Spring Reactive SSE Example (https://blog.davidvassallo.me/3170)
package com.example.sse.routers
import com.example.sse.HomeHandler
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.MediaType
import org.springframework.web.reactive.function.server.HandlerFunction
import org.springframework.web.reactive.function.server.RequestPredicates
import org.springframework.web.reactive.function.server.RouterFunction
import org.springframework.web.reactive.function.server.RouterFunctions
import org.springframework.web.reactive.function.server.ServerResponse
@Configuration
class DefaultRouter{
@Bean
fun route(homeHandler: HomeHandler): RouterFunction<ServerResponse> {
return RouterFunctions
.route(RequestPredicates.GET("/sse").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
HandlerFunction<ServerResponse> { homeHandler.ssEvents(it) })
}
}
package com.example.sse.handlers
import com.example.sse.services.ServerSideEvents
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.codec.multipart.FilePart
import org.springframework.http.codec.multipart.Part
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.BodyExtractors
import org.springframework.web.reactive.function.BodyInserters
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.bodyToServerSentEvents
import reactor.core.publisher.Mono
@Component
class HomeHandler {
@Autowired
var sseService : ServerSideEvents ?= null
fun ssEvents(request: ServerRequest): Mono<ServerResponse> {
val sseEvents = sseService!!.getSSE()
println(request.headers().host().toString())
return ServerResponse.ok().bodyToServerSentEvents(sseEvents)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment