Skip to content

Instantly share code, notes, and snippets.

@dvas0004
Last active July 9, 2018 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvas0004/5396151ca105ebcff137cbe199491b6b to your computer and use it in GitHub Desktop.
Save dvas0004/5396151ca105ebcff137cbe199491b6b to your computer and use it in GitHub Desktop.
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