Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

RSocket is an application protocol providing Reactive Streams semantics – it functions, for example, as an alternative to HTTP.

In this tutorial, we’re going to look at RSocket using Spring Boot, and specifically how it helps abstract away the lower-level RSocket API.

2. Dependencies

Let’s start with adding the spring-boot-starter-rsocket dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-rsocket</artifactId>
</dependency>

This will transitively pull in RSocket related dependencies such as rsocket-core and rsocket-transport-netty.

3. Sample Application

Now we’ll continue with our sample application. To highlight the interaction models RSocket provides, we’re going to create a trader application. Our trader application will consist of a client and a server.

3.1. Server Setup

First, let’s set up the server, which will be a Spring Boot application bootstrapping an RSocket server.

Since we have the spring-boot-starter-rsocket dependency, Spring Boot autoconfigures an RSocket server for us. As usual with Spring Boot, we can change default configuration values for the RSocket server in a property-driven fashion.

For example, let’s change the port of our RSocket server by adding the following line to our application.properties file:

spring.rsocket.server.port=7000

We can also change other properties to further modify our server according to our needs.

3.2. Client Setup

Next, let’s set up the client which will also be a Spring Boot application.

Although Spring Boot auto-configures most of the RSocket related components, we should also define some beans to complete the setup:

@Configuration
public class ClientConfiguration {

    @Bean
    public RSocketRequester getRSocketRequester(){
        RSocketRequester.Builder builder = RSocketRequester.builder();

        return builder
          .rsocketConnector(
             rSocketConnector ->
               rSocketConnector.reconnect(Retry.fixedDelay(2, Duration.ofSeconds(2)))
          )
          .dataMimeType(MimeTypeUtils.APPLICATION_JSON)
          .tcp("localhost", 7000);
    }
}

Here we’re creating the RSocket client and configuring it to use TCP transport on port 7000. Note that this is the server port we’ve configured previously.

After defining this bean configuration, we have a bare-bones structure.

Next, we’ll explore different interaction models and see how Spring Boot helps us there.

4. Request/Response with RSocket and Spring Boot

Let’s start with Request/Response. This is probably the most common and familiar interaction model since HTTP also employs this type of communication.

In this interaction model, the client initiates the communication and sends a request. Afterward, the server performs the operation and returns a response to the client – thus the communication completes.

In our trader application, a client will ask for the current market data of a given stock. In return, the server will pass the requested data.

4.1. Server

On the server side, we should first create a controller to hold our handler methods. But instead of @RequestMapping or @GetMapping annotations like in Spring MVC, we will use the @MessageMapping annotation:

@Controller
public class MarketDataRSocketController {

    private final MarketDataRepository marketDataRepository;

    public MarketDataRSocketController(MarketDataRepository marketDataRepository) {
        this.marketDataRepository = marketDataRepository;
    }

    @MessageMapping("currentMarketData")
    public Mono<MarketData> currentMarketData(MarketDataRequest marketDataRequest) {
        return marketDataRepository.getOne(marketDataRequest.getStock());
    }
}

So let’s investigate our controller.

We’re using the @Controller annotation to define a handler which should process incoming RSocket requests. Additionally, the @MessageMapping annotation lets us define which route we’re interested in and how to react upon a request.

In this case, the server listens for the currentMarketData route, which returns a single result to the client as a Mono<MarketData>.

4.2. Client

Next, our RSocket client should ask for the current price of a stock and get a single response.

To initiate the request, we should use the RSocketRequester class:

@RestController
public class MarketDataRestController {

    private final RSocketRequester rSocketRequester;

    public MarketDataRestController(RSocketRequester rSocketRequester) {
        this.rSocketRequester = rSocketRequester;
    }

    @GetMapping(value = "/current/{stock}")
    public Publisher<MarketData> current(@PathVariable("stock") String stock) {
        return rSocketRequester
          .route("currentMarketData")
          .data(new MarketDataRequest(stock))
          .retrieveMono(MarketData.class);
    }
}

Note that in our case, the RSocket client is also a REST controller from which we call our RSocket server. So, we’re using @RestController and @GetMapping to define our request/response endpoint.

In the endpoint method, we’re using RSocketRequester and specifying the route. In fact, this is the route which the RSocket server expects. Then we’re passing the request data. And lastly, when we call the retrieveMono() method, Spring Boot initiates a request/response interaction.

5. Fire and Forget With RSocket and Spring Boot

Next, we’ll look at the fire-and-forget interaction model. As the name implies, the client sends a request to the server but doesn’t expect a response back.

In our trader application, some clients will serve as a data source and will push market data to the server.

5.1. Server

Let’s create another endpoint in our server application:

@MessageMapping("collectMarketData")
public Mono<Void> collectMarketData(MarketData marketData) {
    marketDataRepository.add(marketData);
    return Mono.empty();
}

Again, we’re defining a new @MessageMapping with the route value of collectMarketData. Furthermore, Spring Boot automatically converts the incoming payload to a MarketData instance.

The big difference here, though, is that we return a Mono<Void> since the client doesn’t need a response from us.

5.2. Client

Let’s see how we can initiate our fire-and-forget request.

We’ll create another REST endpoint:

@GetMapping(value = "/collect")
public Publisher<Void> collect() {
    return rSocketRequester
      .route("collectMarketData")
      .data(getMarketData())
      .send();
}

Here we’re specifying our route and our payload will be a MarketData instance. Since we’re using the send() method to initiate the request instead of retrieveMono(), the interaction model becomes fire-and-forget.

6. Request Stream with RSocket and Spring Boot

Request streaming is a more involved interaction model, where the client sends a request but gets multiple responses over the course of time from the server.

To simulate this interaction model, a client will ask for all market data of a given stock.

6.1. Server

Let’s start with our server. We’ll add another message mapping method:

@MessageMapping("feedMarketData")
public Flux<MarketData> feedMarketData(MarketDataRequest marketDataRequest) {
    return marketDataRepository.getAll(marketDataRequest.getStock());
}

As we can see, this handler method is very similar to the other ones. The different part is that we returning a Flux<MarketData> instead of a Mono<MarketData>. In the end, our RSocket server will send multiple responses to the client.

6.2. Client

On the client side, we should create an endpoint to initiate our request/stream communication:

@GetMapping(value = "/feed/{stock}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Publisher<MarketData> feed(@PathVariable("stock") String stock) {
    return rSocketRequester
      .route("feedMarketData")
      .data(new MarketDataRequest(stock))
      .retrieveFlux(MarketData.class);
}

Let’s investigate our RSocket request.

First, we’re defining the route and request payload. Then, we’re defining our response expectation with the retrieveFlux() method call. This is the part which determines the interaction model.

Also note that, since our client is also a REST server, it defines response media type as MediaType.TEXT_EVENT_STREAM_VALUE.

7. Exception Handling

Now let’s see how we can handle exceptions in our server application in a declarative way.

When doing request/response, we can simply use the @MessageExceptionHandler annotation:

@MessageExceptionHandler
public Mono<MarketData> handleException(Exception e) {
    return Mono.just(MarketData.fromException(e));
}

Here we’ve annotated our exception handler method with @MessageExceptionHandler. As a result, it will handle all types of exceptions since the Exception class is the superclass of all others.

We can be more specific and create different exception handler methods for different exception types.

This is of course for the request/response model, and so we’re returning a Mono<MarketData>. We want our return type here to match the return type of our interaction model.

8. Summary

In this tutorial, we’ve covered Spring Boot’s RSocket support and detailed different interaction models RSocket provides.

As always, you can check out all the code samples over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – Junit (guide) (cat=Reactive)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!