How to create Reactive REST API with filter in Spring Boot

Spring Boot Reactive Restful API with reactive streaming Examples

Purpose: In this guide, I want to show how easy it is to create a reactive REST API with a filter using 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 department-wise without refreshing the page.

1. Create reactive API Visit hereHow to create Reactive REST API in Spring Boot.

Next Step. Create Rest Controller to filter the employee based on department and stream the employee.

package com.bce.controller;

import java.util.function.Predicate;

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.PathVariable;
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;

@RestController
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    @Autowired
    private Sinks.Many<Employee> employeeStream;

    @PostMapping("/employee")
    public void saveEmployee(@RequestBody Employee employee) {
        employeeService.processRecords(employee);
    }
   

    @GetMapping(value = "/employeeStream/{dept}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<Employee>> getLeadData(@PathVariable String dept) {
       
        Predicate<Employee> departmentEquals = e -> e.getDepartment().equals(dept);
   
        return employeeStream.asFlux().filter(departmentEquals)
                .map(data -> ServerSentEvent.builder(data).build());
    }

}

Next Step: The default server port is 8080. Wish you want to change open 

server.port=8080

Next Step. Run the application and open the below URI  to view the employee http://localhost:8080/api/employeeStream/CO. To create an employee use this endpoint http://localhost:8080/api/employee

In the below screen, we are creating employees and streaming them in real-time.





Download Code from GitHub.  Download

No comments:

Post a Comment