I have a Swift NIO HTTP2 server which handles request within the context's event loop. But I want to process the request in another thread, GCD aync thread pool and get the result back and send it.
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
context.eventLoop.execute {
context.channel.getOption(HTTP2StreamChannelOptions.streamID).flatMap { streamID -> EventLoopFuture<Void> in
// ...
var buffer = context.channel.allocator.buffer(capacity: respBody.count)
buffer.writeString(respBody)
context.channel.write(self.wrapOutboundOut(HTTPServerResponsePart.body(.byteBuffer(buffer))), promise: nil)
return context.channel.writeAndFlush(self.wrapOutboundOut(HTTPServerResponsePart.end(nil)))
}.whenComplete { _ in
context.close(promise: nil)
}
}
}
If I change it to use GCD global queue, how would I return the EventLoopFuture<Void>
response?
context.eventLoop.execute {
context.channel.getOption(HTTP2StreamChannelOptions.streamID).flatMap { streamID -> EventLoopFuture<Void> in
DispatchQueue.global().async {
return self.send("hello world new ok", to: context.channel).whenComplete({ _ in
_ = context.channel.writeAndFlush(self.wrapOutboundOut(HTTPServerResponsePart.end(nil)))
context.close(promise: nil)
})
}
}
}
Is it okay to use GCD global queue in this way or how will I use worker threads?
The send string function calls the below function to write the body.
private func sendData(_ data: Data, to channel: Channel, context: StreamContext) -> EventLoopFuture<Void> {
let headers = self.getHeaders(contentLength: data.count, context: context)
_ = self.sendHeader(status: .ok, headers: headers, to: channel, context: context)
var buffer = channel.allocator.buffer(capacity: data.count)
buffer.writeBytes(data)
let part = HTTPServerResponsePart.body(.byteBuffer(buffer))
return channel.writeAndFlush(part)
}