英文:
Does cancelling the context for a query using the MongoDB Go driver affect running operations on the server?
问题
当Go驱动程序检测到上下文被取消时,我认为它会使连接处于空闲状态并将其返回到连接池中。这是否意味着它启动的正在运行的数据库操作也会在服务器上被终止?还是会继续执行下去?
英文:
When the Go driver detects that a context is cancelled, I think it will idle the connection and return it to the pool. Does that imply the running DB operation that it started will also be killed on the server? Or does that continue on?
答案1
得分: 2
你可以阅读关于驱动程序如何使用上下文的官方文档。
相关部分:套接字读取和写入:
当驱动程序检索到用于操作的连接时,它会将套接字的读取或写入截止时间设置为上下文截止时间或套接字超时时间中较短的那个。
如果在
Read()
或Write()
函数执行后但在其截止时间之前取消上下文,驱动程序的行为会根据版本而有所不同。当
Read()
或Write()
函数正在进行时,驱动程序会生成一个单独的goroutine来监听上下文的取消。**如果goroutine检测到取消操作,它会关闭连接。**待处理的Read()
或Write()
函数会返回一个错误,驱动程序会用context.Canceled
错误覆盖该错误。
请注意,关闭连接只是将其放回空闲池中。关于在服务器上取消操作并没有明确的说明,但显然会发送一个信号,表示客户端放弃了该操作并不再监视/关心结果。如果可能的话,MongoDB服务器会中止已启动的操作。例如,如果操作是一个查询,那么可以中止它。如果是写操作(如插入或更新),则可能无法中止。
英文:
You can read the official documentation about how the driver uses the context here.
Relevant section: Socket Read and Write:
> When the driver retrieves a connection for an operation, it sets the socket’s read or write deadline to either the Context deadline or socket timeout, whichever is shorter.
>
> If you cancel the Context after the execution of the Read()
or Write()
function but before its deadline, the behavior of the driver differs based on version.
>
> The driver generates a separate goroutine to listen for Context cancellation when the Read()
or Write()
function is in progress. If the goroutine detects a cancellation, it closes the connection. The pending Read()
or Write()
function returns an error which the driver overwrites with the context.Canceled
error.
Note that closing the connection just means putting it back to the pool as idle. There is no explict statement about cancelling the operation on the server, but obviously a signal is sent that the client abandons the operation and no longer monitors / cares for the result. The MongoDB server would be dumb not to abort the initiated operation if it can be. For example if the operation was a query, that can be aborted. If it was a write operation (such as insert or update), that may not be aborted.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论