Go 如何在连接关闭时终止正在运行的查询

Go 如何在连接关闭时终止正在运行的查询,go,go-gorm,Go,Go Gorm,我们在后端使用ORM和脚本连接到PostgreSQL数据库 有时,当脚本正在进行时,我们通过在本地按Ctrl+C或在生产中终止pod/进程来手动终止作业。我们在所有脚本中都有一个defer DB.Close,我还添加了处理SIGINT/SIGTERM信号来执行DB.Close on kill 问题是,即使在关闭连接之后,已经运行的任何现有查询也不会被终止并继续占用数据库资源。在直接从gorm或通过其他黑客退出之前,是否有办法终止此连接池启动的任何查询 考虑使用pg_backend_pid并使用p

我们在后端使用ORM和脚本连接到PostgreSQL数据库

有时,当脚本正在进行时,我们通过在本地按Ctrl+C或在生产中终止pod/进程来手动终止作业。我们在所有脚本中都有一个defer DB.Close,我还添加了处理SIGINT/SIGTERM信号来执行DB.Close on kill

问题是,即使在关闭连接之后,已经运行的任何现有查询也不会被终止并继续占用数据库资源。在直接从gorm或通过其他黑客退出之前,是否有办法终止此连接池启动的任何查询

考虑使用pg_backend_pid并使用pg_stat_活动终止查询,但是我们在运行新的pg_backend_pid时得到的pid将与运行中的pid不同

版本:jinzhu/gorm v1.9.2

您可以开始使用xctx context.context,opts*sql.TxOptions,它将上下文作为参数

下面是一个小例子:


import (
    "context"
    "fmt"
    "os"
    "os/signal"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
)

func main() {
    db, err := gorm.Open("postgres", "host=localhost port=5432 user=gorm dbname=gorm password=mypassword sslmode=disable")
    if err != nil {
        panic(err)
    }
    defer db.Close()
    ctx := context.Background()

    ctx, cancel := context.WithCancel(ctx)
    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt)
    defer func() {
        signal.Stop(c)
        cancel()
    }()
    go func() {
        select {
        case <-c:
            cancel()
        case <-ctx.Done():
        }
    }()

    transaction, err := db.DB().BeginTx(ctx, nil)
    _, err = transaction.Exec("SELECT pg_sleep(100)")
    if err != nil {
        fmt.Println(err.Error())
    }
}
您可以使用BeginTxctx context.context,opts*sql.TxOptions,它将上下文作为参数

下面是一个小例子:


import (
    "context"
    "fmt"
    "os"
    "os/signal"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
)

func main() {
    db, err := gorm.Open("postgres", "host=localhost port=5432 user=gorm dbname=gorm password=mypassword sslmode=disable")
    if err != nil {
        panic(err)
    }
    defer db.Close()
    ctx := context.Background()

    ctx, cancel := context.WithCancel(ctx)
    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt)
    defer func() {
        signal.Stop(c)
        cancel()
    }()
    go func() {
        select {
        case <-c:
            cancel()
        case <-ctx.Done():
        }
    }()

    transaction, err := db.DB().BeginTx(ctx, nil)
    _, err = transaction.Exec("SELECT pg_sleep(100)")
    if err != nil {
        fmt.Println(err.Error())
    }
}

这就是上下文。上下文是用来做什么的。你读过了吗?看docsAlso的地图处理停止信号。例如,如本文所述,感谢@Flimzy@Matteo。gorm文档中提到的db.WithContext方法似乎不可用。我们目前的版本是v1金珠/gormv1.9.2。如果有什么例子我可以看一下,那将非常有帮助。同时也会阅读上下文。这就是上下文。上下文是用来做什么的。你读过了吗?看docsAlso的地图处理停止信号。例如,如本文所述,感谢@Flimzy@Matteo。gorm文档中提到的db.WithContext方法似乎不可用。我们目前的版本是v1金珠/gormv1.9.2。如果有什么例子我可以看一下,那将非常有帮助。同时,我也将阅读上下文。