我有一个 Swift NIO HTTP2 服务器,它在上下文的事件循环中处理请求。但我想在另一个线程中处理请求,GCD aync 线程池并取回结果并发送它。
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)
}
}
}
如果我将其更改为使用 GCD 全局队列,我将如何返回EventLoopFuture<Void>
响应?
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)
})
}
}
}
以这种方式使用 GCD 全局队列是否可以,或者我将如何使用工作线程?
发送字符串函数调用下面的函数来编写正文。
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)
}