我正在使用Webflux 2.1.8在Spring Boot 2.1.3中构建一个UDP服务器,该服务器从UDP客户端收集数据。
我希望以完全反应的方式构建它,但是我面临线程池的问题。我的应用程序当前仅在一个线程上运行,这不是我期望的。首先,我建立了一个简单的python客户端,它等待响应来测试我的服务器
# Create a UDP socket at client side
UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# Send to server using created UDP socket
UDPClientSocket.sendto(bytesToSend, serverAddressPort)
print("Receiving...")
msgFromServer = UDPClientSocket.recvfrom(bufferSize)
msg = "Message from Server {}".format(msgFromServer[0])
print(msg)
现在我的Spring Boot UDP服务器看起来像这样:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
CommandLineRunner serverRunner(UdpDecoderHandler udpDecoderHanlder, UdpEncoderHandler udpEncoderHandler, UdpHandler udpHandler) {
return strings -> {
createUdpServer(udpDecoderHanlder, udpEncoderHandler, udpHandler);
};
}
private void createUdpServer(UdpDecoderHandler udpDecoderHandler, UdpEncoderHandler udpEncoderHandler, UdpHandler udpHandler) {
UdpServer.create()
.handle((in,out) -> {
in.receive().asByteArray().subscribe();
return Flux.never();
})
.port(19001)
.doOnBound(conn -> conn
.addHandler("decoder", udpDecoderHandler)
.addHandler("encoder", udpEncoderHandler)
.addHandler("handler", udpHandler)
)
.bindNow(Duration.ofSeconds(30));
}
}
解码器:
@Service
public class UdpDecoderHandler extends MessageToMessageDecoder<DatagramPacket> {
private static final Logger LOGGER = LoggerFactory.getLogger(UdpDecoderHandler.class);
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket, List<Object> out) {
ByteBuf byteBuf = datagramPacket.content();
byte[] data = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(data);
String msg = new String(data);
LOGGER.info("Decoded data: " + msg);
InetSocketAddress s = datagramPacket.sender();
channelHandlerContext.fireChannelRead(s);
}
}
编码器:
@Service
public class UdpEncoderHandler extends MessageToMessageEncoder {
@Override
protected void encode(ChannelHandlerContext ctx, Object o, List list) throws Exception {
InetSocketAddress socketAddress = (InetSocketAddress) o;
log.debug("Encode function...");
String msg = "Hello response!";
DatagramPacket response = new DatagramPacket(Unpooled.copiedBuffer(msg.getBytes()), socketAddress);
list.add(response);
}
}
处理程序(在这里我添加了睡眠功能以测试我的并发性):
@Service
public class UdpHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
log.info("Channel Read function");
InetSocketAddress message = (InetSocketAddress) msg;
Thread.sleep(5000);
ctx.channel().writeAndFlush(message).addListener((GenericFutureListener<Future<Void>>) future -> {
if(future.isDone() && future.isSuccess()) {
log.info("OK");
} else {
log.error("error " + future.isDone() + " - " + future.isSuccess());
if(!future.isSuccess()) {
future.cause().printStackTrace();
}
}
});
}
}
这样我就立即运行了python脚本:
python3 udp-client.py & python3 udp-client.py
将弹出两条消息,两者之间的差值为5s,这意味着我的应用程序在一个线程上运行。
如何自定义netty和webflux以使用4个线程?