Spring Boot Reactive Restful API with In-memory database reactive streaming Examples
Purpose: In this guide, I want to show how easy it is to create a reactive REST API with Spring Boot and save data into an in-memory database. I would like to take a simple Use Case to show how quick it is possible to create an “active” non-blocking REST API with Spring Boot.
Case Study:: In this case study we will register the employee at the company front gate and will show the registered employee in the company interview room without refreshing the page and will save it into the database.
1. Setup and Create Project: Visit here. Spring Boot Rest API Hello World Examples.
Next Step. Spring Boot Parent Dependencies.
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.7</version><relativePath /> <!-- lookup parent from repository --></parent>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId></dependency>
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId></dependency>
package com.bce;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;import com.bce.model.Employee;import reactor.core.publisher.Sinks;@SpringBootApplicationpublic class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}// Reactive sink bean create here and it will return the latest object@Bean("empoyeePublisher")public Sinks.Many<Employee> sink(){return Sinks.many().replay().latest();}}
package com.bce.controller;import java.util.concurrent.atomic.AtomicLong;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.MediaType;import org.springframework.http.codec.ServerSentEvent;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;import com.bce.model.Employee;import com.bce.service.EmployeeService;import reactor.core.publisher.Flux;import reactor.core.publisher.Sinks;@RestControllerpublic class EmployeeController {@AutowiredEmployeeService employeeService;@Autowiredprivate Sinks.Many<Employee> employeeStream;final AtomicLong counter = new AtomicLong();@PostMapping("/employee")public void saveEmployee(@RequestBody Employee employee) {employeeService.processRecords(employee);}@GetMapping(value = "/employeeStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)public Flux<ServerSentEvent<Employee>> employeeStream() {return employeeStream.asFlux().map(e -> ServerSentEvent.builder(e).build());}}
No comments:
Post a Comment