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

我们在后端使用 https://github.com/go-gorm/gorm/ ORM和脚本来连接到我们的PostgreSQL数据库。

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

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

想到使用 和 终止查询 使用 ,但是我们在运行新查询时获得的 pid 将与正在运行的查询不同。pg_backend_pid()pg_stat_activitypg_backend_pid()

版本jinzhu/gorm v1.9.2


慕标5832272
浏览 84回答 1
1回答

慕后森

您可以使用 将上下文作为参数。BeginTx(ctx context.Context, opts *sql.TxOptions)这里有一个小例子:import (&nbsp; &nbsp; "context"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "os"&nbsp; &nbsp; "os/signal"&nbsp; &nbsp; "github.com/jinzhu/gorm"&nbsp; &nbsp; _ "github.com/jinzhu/gorm/dialects/postgres")func main() {&nbsp; &nbsp; db, err := gorm.Open("postgres", "host=localhost port=5432 user=gorm dbname=gorm password=mypassword sslmode=disable")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; defer db.Close()&nbsp; &nbsp; ctx := context.Background()&nbsp; &nbsp; ctx, cancel := context.WithCancel(ctx)&nbsp; &nbsp; c := make(chan os.Signal, 1)&nbsp; &nbsp; signal.Notify(c, os.Interrupt)&nbsp; &nbsp; defer func() {&nbsp; &nbsp; &nbsp; &nbsp; signal.Stop(c)&nbsp; &nbsp; &nbsp; &nbsp; cancel()&nbsp; &nbsp; }()&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <-c:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cancel()&nbsp; &nbsp; &nbsp; &nbsp; case <-ctx.Done():&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }()&nbsp; &nbsp; transaction, err := db.DB().BeginTx(ctx, nil)&nbsp; &nbsp; _, err = transaction.Exec("SELECT pg_sleep(100)")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err.Error())&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go