Skip to content

Instantly share code, notes, and snippets.

@alexcheng1982
Created November 6, 2017 09:31
Show Gist options
  • Save alexcheng1982/7a00ec282563f1b0aa952a8f9c68eea4 to your computer and use it in GitHub Desktop.
Save alexcheng1982/7a00ec282563f1b0aa952a8f9c68eea4 to your computer and use it in GitHub Desktop.
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.util.function.Tuples;
import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;
@RestController
@RequestMapping("/sse")
public class SseController {
@GetMapping("/randomNumbers")
public Flux<ServerSentEvent<Integer>> randomNumbers() {
return Flux.interval(Duration.ofSeconds(1))
.map(seq -> Tuples.of(seq, ThreadLocalRandom.current().nextInt()))
.map(data -> ServerSentEvent.<Integer>builder()
.event("random")
.id(Long.toString(data.getT1()))
.data(data.getT2())
.build());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment