Open In App

Spring Webflux Vs Rsocket

Last Updated : 25 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Spring WebFlux and RSocket are tools offered by the Spring ecosystem for developing reactive applications. Their functions and features are different. Spring Webflux, Reactive stream semantics for non-blocking activities may be implemented in a web application. RSocket, reactive Stream semantics between client-server and server-server communication are supported.

In this article, we will learn about Spring Webflux vs Rsocket.

Spring Webflux in Spring Boot

Below are the steps to implement Spring WebFlux in the Spring Boot Application.

Step 1: Add Maven Dependencies

First, let’s import all other necessary dependencies using the spring-boot-starter-web flux dependency:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>4.2.7</version>
</dependency>

Step 2: Create an annotated EmployeeController

To publish a reactive stream of the Employee resource, we first establish an annotated controller on the server.

Java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/employees")
public class EmployeeController {

    private final EmployeeRepository employeeRepository;

    // Constructor injection to inject EmployeeRepository bean
    public EmployeeController(EmployeeRepository employeeRepository) {
        this.employeeRepository = employeeRepository;
    }

    // Other controller methods can go here...
}
  • This is a Spring MVC controller class EmployeeController responsible for handling HTTP requests related to employees.
  • It is mapped to the /employees endpoint.
  • The constructor injects an instance of EmployeeRepository, allowing the controller to interact with the persistence layer for managing employee data.

Step 3: Create SecurityConfig

Let’s build SecurityConfig and specify some path-based restrictions to enable only ADMIN users in order to limit access to this method:

Java
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;

@EnableWebFluxSecurity
public class EmployeeWebSecurityConfig {

    // This method configures security filters for web requests
    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(
      ServerHttpSecurity http) {
        // Disables Cross-Site Request Forgery (CSRF) protection
        http.csrf().disable()
          // Configures authorization rules for different endpoints
          .authorizeExchange()
          // Requires "ADMIN" role for POST requests to "/employees/update"
          .pathMatchers(HttpMethod.POST, "/employees/update").hasRole("ADMIN")
          // Allows access to all other endpoints without authentication
          .pathMatchers("/**").permitAll()
          // Configures HTTP Basic authentication
          .and()
          .httpBasic();
        // Builds the SecurityWebFilterChain with the configured rules
        return http.build();
    }
}
  • This Spring Security configuration class EmployeeWebSecurityConfig enables security for a WebFlux application.
  • It defines security rules for various endpoints, allowing unrestricted access to most endpoints while requiring the “ADMIN” role for POST requests to “/employees/update”.
  • Additionally, it configures HTTP Basic authentication and disables Cross-Site Request Forgery (CSRF) protection.

Rsocket in Spring Boot

Below are the steps to use Rsocket in Spring Boot application.

Step 1: Add Maven Dependencies

Two direct dependencies are all that RSocket needs.Reactive networking protocol RSocket and its Netty-based transport implementation may be used to provide robust and reactive service-to-service communication.

<dependency>
<groupId>io.rsocket</groupId>
<artifactId>rsocket-core</artifactId>
<version>1.7.13</version>
</dependency>
<dependency>
<groupId>io.rsocket</groupId>
<artifactId>rsocket-transport-netty</artifactId>
<version>1.7.13</version>
</dependency>

Step 2: Use the RSocketRequester class

The next step is for our RSocket client to request the stock’s current price and receive a single answer. We should use the RSocketRequester class to start the request:

Java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.reactivestreams.Publisher;
import org.springframework.messaging.rsocket.RSocketRequester;

@RestController
public class MarketDataRestController {

    private final RSocketRequester rSocketRequester;

    // Constructor injection to inject RSocketRequester bean
    public MarketDataRestController(RSocketRequester rSocketRequester) {
        this.rSocketRequester = rSocketRequester;
    }

    // Endpoint to retrieve current market data for a given stock
    @GetMapping(value = "/current/{stock}")
    public Publisher<MarketData> current(@PathVariable("stock") String stock) {
        // Sending a request to the RSocket server with the route "currentMarketData"
        // and providing data which is an instance of MarketDataRequest containing the stock symbol
        // RetrieveMono is used to retrieve a single response of MarketData
        return rSocketRequester
          .route("currentMarketData")
          .data(new MarketDataRequest(stock))
          .retrieveMono(MarketData.class);
    }
}
  • This code snippet represents a Spring WebFlux REST controller named MarketDataRestController.
  • It handles GET requests to retrieve current market data for a given stock.
  • It utilizes RSocket communication to asynchronously fetch market data from a remote service using a reactive stream (Publisher) and returns a single response of MarketData.

Step 3: Create an Endpoint

In our server application, let’s establish an endpoint. We are defining a new @MessageMapping with the route value collectMarketData.

Java
import org.springframework.messaging.handler.annotation.MessageMapping;
import reactor.core.publisher.Mono;

// Annotates the method to handle messages with the destination "collectMarketData"
@MessageMapping("collectMarketData")
public Mono<Void> collectMarketData(MarketData marketData) {
    // Assuming marketDataRepository is some repository for storing market data
    // Adds the received market data to the repository
    marketDataRepository.add(marketData);
    
    // Indicates completion of the processing without any data to return
    return Mono.empty();
}
  • This code defines a method collectMarketData annotated with @MessageMapping, indicating it handles messages with the destination “collectMarketData” in a messaging system.
  • Upon receiving a MarketData object, it stores it in a repository (marketDataRepository) and returns a Mono<Void> to indicate completion of processing without any data to return.

Difference between Spring Webflux and Rsocket

Spring Webflux

Rsocket

Spring Webflux is a reactive stream semantics for non-blocking activities may be implemented in a web application.

RSocket is a binary point-to-point communication protocol designed for distributed applications. It offers an alternative to existing protocols, such as HTTP, in that regard.

Reactive stream programming is less supported by Webflux.

Reactive stream programming is better supported by RSocket, which is also quicker, more sophisticated, and has more options.

HTTP request-response is supported by Spring Webflux.

A protocol for reactive streams called RSocket uses Websocket and TCP. It allows for request and streaming, fire and forget, and request and answer.Two-way streaming.

The data is sent as JSON in Spring Webflux.

It is transmitted as Binary via RSocket.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads