I'm trying to learn Spring webflux & R2DBC. The one I try is simple use case:
- have a
book
table - create an API (
/books
) that provides text stream and returningFlux<Book>
- I'm hoping when I hit
/books
once, keep my browser open, and any new data inserted tobook
table, it will send the new data to browser.
Scenario 2, still from book
table:
- have a
book
table - create an API (
/books/count
) that returning count of data inbook
asMono<Long>
- I'm hoping when I hit
/books/count
once, keep my browser open, and any new data inserted /deleted tobook
table, it will send the new count to browser.
But it does not works. After I isnsert new data, no data sent to any of my endpoint.
I need to hit /books
or /books/count
to get the updated data.
I think to do this, I need to use Server Sent Events? But how to do this in and also querying data? Most sample I got is simple SSE that sends string every certain interval.
Any sample to do this?
Here is my BookApi.java
@RestController
@RequestMapping(value = "/books")
public class BookApi {
private final BookRepository bookRepository;
public BookApi(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Book> getAllBooks() {
return bookRepository.findAll();
}
@GetMapping(value = "/count", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Mono<Long> count() {
return bookRepository.count();
}
}
BookRepository.java (R2DBC)
import org.springframework.data.r2dbc.repository.R2dbcRepository;
public interface BookRepository extends R2dbcRepository<Book, Long> {
}
Book.java
@Table("book")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
@Id
private Long id;
@Column(value = "name")
private String name;
@Column(value = "author")
private String author;
}