生成许多​​通知时,与posgres数据库的连接即将关闭

时间:2019-07-12 01:12:13

标签: postgresql npgsql

我有一个线程,用于侦听postgres通知,然后发送要由我的.NET Core应用程序处理的线程。当在数据库上发生导致大量通知的操作时,与数据库的NPgSQLConnection将关闭。

用于侦听通知的代码如下。它在托管服务中执行。

public async Task WaitForNotificationEvent(int timeout)
        {
            await Task.Run(() =>
            {
                lock (_connection)
                {
                    try
                    {
                        if (_connection.State == ConnectionState.Closed)
                        {
                            _logger.LogWarning("Notification connection to the database is unexpectantly closed");
                            // If the connection has been closed we must reopen it and listen for the known notifications.
                            foreach (var channel in _channels)
                            {
                                _logger.LogWarning($"Attempting to resubscribe to '{channel}' notifications");
                                Listen(channel);
                            }
                        }

                        _connection.Wait(timeout);
                    }
                    catch
                    {
                        Thread.Sleep(timeout);
                    }
                }
            });
        }

在上面的代码中,我不希望看到意外的连接关闭消息。但是,当收到许多通知时,我会这样做。

在postgres日志中,我发现无法从客户端接收数据:远程主机强行关闭了现有连接。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

我遇到了与此处所述相同的问题:https://github.com/npgsql/npgsql/issues/2337

我终于可以正常工作了。

当要检索的通知很多时会超时。

在网上搜索后,我发现您可以在NPgSQLConnection上设置超时。

我确切不知道什么设置可以解决它,但是我设置了以下连接设置:

CommandTimeout = 0
InternalCommandTimeout = 0
KeepAlive = 30
Pooling = false
TcpKeepAlive = true
Timeout = 0