Fork me on GitHub

Reactive Tutorial

This tutorial demonstrates using Reactive logic within WoOF.

It will use the WebClientManagedObjectSource to make an asynchronous call to another REST end point.

To avoid having to start multiple servers, the call will be back onto a REST end point of the same server. As such, the configuration for this tutorial is the following:

ReactorHttpServer screen shot.

Tutorial Source

Server

Before getting to the Reactive logic, the Server logic that is called asynchronously is the following:

public class ServerLogic {

	public void service(ObjectResponse<ServerResponse> response) {
		response.send(new ServerResponse("TEST"));
	}
}

With the following response object:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ServerResponse {
	private String message;
}

This is very simple, however, will show how the Reactive logic can call this end point asynchronously.

Reactive logic

To enable the returned Reator types to be handled natively by OfficeFloor, add the following:

		<dependency>
			<groupId>net.officefloor.reactor</groupId>
			<artifactId>officereactor</artifactId>
		</dependency>

The following is the reactive logic to call the above server:

	public Mono<ServerResponse> reactive(WebClient client) {
		return client.get().uri("http://localhost:7878/server").accept(MediaType.APPLICATION_JSON).retrieve()
				.bodyToMono(ServerResponse.class);
	}

OfficeFloor will subscribe to the returned Mono. The success is passed as parameter to the next procedure (sending it as response):

	public void send(@Parameter ServerResponse result, ObjectResponse<ServerResponse> response) {
		response.send(result);
	}

Should the Mono fail, OfficeFloor will route the exception to the appropriate exception handler. See Exception Tutorial for more details.

Spring WebClient

To have the Spring WebClient available, add the following:

		<dependency>
			<groupId>net.officefloor.spring</groupId>
			<artifactId>officespring_webclient</artifactId>
		</dependency>

then configure as follows in application.objects:

<objects>

	<managed-object source="net.officefloor.spring.webclient.WebClientManagedObjectSource" />

</objects>

Testing

The following shows invoking the reactive code that asynchronously pulls data from the server:

@ExtendWith(OfficeFloorExtension.class)
public class ReactorHttpServerTest {

	@RegisterExtension
	public HttpClientExtension httpClient = new HttpClientExtension();

	@Test
	public void retreiveResult() throws Exception {
		HttpResponse response = this.httpClient.execute(new HttpGet("http://localhost:7878/reactive"));
		assertEquals(200, response.getStatusLine().getStatusCode(), "Should be successful");
		assertEquals("{\"message\":\"TEST\"}", EntityUtils.toString(response.getEntity()), "Incorrect response");
	}
}

Next

The next tutorial covers using R2DBC.