tutorial real time event streaming with spring webflux
This commit is contained in:
parent
274745e3bb
commit
0da695fba5
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.reactive.webflux;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class Event {
|
||||
|
||||
private Long id;
|
||||
private String body;
|
||||
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.reactive.webflux;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
@RestController
|
||||
public class EventStreamController {
|
||||
|
||||
@GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public Flux<Event> getMessages() {
|
||||
return Flux.interval(Duration.ofMillis(1000))
|
||||
.map(tick -> new Event(tick, "This is Message #" + tick));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.reactive.webflux;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class WebfluxDemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(WebfluxDemoApplication.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Baeldung: Spring 5 Reactive Webflux - real time event streaming</title>
|
||||
|
||||
<style type="text/css">
|
||||
tr:nth-child(even) {background: lightgray}
|
||||
tr:nth-child(odd) {background: white}
|
||||
th {background: gray; text-align: left;}
|
||||
</style>
|
||||
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Events streamed...</h1>
|
||||
|
||||
<table id="events-table" >
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Event Id</th>
|
||||
<th>Event Body</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
</table>
|
||||
|
||||
<script>
|
||||
var eventSource = new EventSource("/events");
|
||||
|
||||
eventSource.onmessage = function (event) {
|
||||
var data = JSON.parse(event.data);
|
||||
var table = document.getElementById("events-table");
|
||||
var row = table.insertRow(1);
|
||||
var cell1 = row.insertCell(0);
|
||||
var cell2 = row.insertCell(1);
|
||||
|
||||
|
||||
cell1.innerHTML = '<td>' + data.id + '</td>';
|
||||
cell2.innerHTML = '<td>' + data.body + '</td>';
|
||||
}
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
Loading…
Reference in New Issue