Let’s assume this is a simple Spring Boot WebFlux application.
Controller:
@RestController
@RequestMapping("/endpoint")
public class SomeController {
private final SomeService service;
@GetMapping("/somepath")
public Mono<String> getSomeString() {
return service.getSomeString();
}
}
Service:
public class SomeService {
public Mono<String> getSomeString() {
return Mono.just("result");
}
}
I need to send the service result via UDP right before the controller sends a response. I found that Netty provides a UdpClient, but there is a lack of examples on how to use it in Spring applications on the Internet.
How can I make a bean that encapsulates UdpClient inside? Is it possible to get a Connection from UdpClient once when the application starts and use it while the application is running? Like this:
@Component
public class UdpSender implements DisposableBean {
private final Connection updConnection;
public UdpSender() {
this.updConnection = UdpClient.create()
.host("localhost")
.port(9876)
.connectNow();
}
public Mono<String> sendStringMessage(String msg) {
return updConnection.outbound().sendString(Mono.just(msg))
.then()
.thenReturn(msg);
}
@Override
public void destroy() throws Exception {
if (updConnection != null) {
updConnection.dispose();
}
}
}
Here is usage that service in controller:
...
private final SomeService service;
private final UdpSender udpSender;
@GetMapping("/somepath")
public Mono<String> getSomeString() {
return service.getSomeString()
.flatMap(str -> udpSender.sendStringMessage(str));
}
...
Will there be any issues with using UdpClient this way? Is it possible to encounter thread blocks or resource leaks with this usage? Are there any other options for integrating UdpClient into a Spring WebFlux application?