在Go中,在http处理程序中使用pgx上下文的正确方法是什么?



更新1似乎使用绑定到HTTP请求的上下文可能会导致"上下文取消"错误。但是,使用context.Background()作为父类似乎可以很好地工作。

// This works, no 'context canceled' errors
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
// However, this creates 'context canceled' errors under mild load
// ctx, cancel := context.WithTimeout(r.Context(), 100*time.Second)
defer cancel()
app.Insert(ctx, record)

(更新了下面的代码示例,以生成一个自包含的repro示例)


在go中,我有一个http处理程序,如以下代码。在对这个端点的第一个HTTP请求中,我得到一个context cancelled错误。但是,数据实际上被插入到数据库中。在对该端点的后续请求中,没有给出此类错误,并且数据也成功插入到数据库中。

:我是否在http处理程序和pgx QueryRow方法之间正确地设置和传递context?(如果没有,有没有更好的方法?)

如果你将这段代码复制到main。转到go run main.go,转到localhost:4444/create并按住ctrl-R以产生温和的负载,您应该看到产生了一些上下文取消错误。

package main
import (
"context"
"fmt"
"log"
"math/rand"
"net/http"
"time"
"github.com/jackc/pgx/v4/pgxpool"
)
type application struct {
DB *pgxpool.Pool
}
type Task struct {
ID     string
Name   string
Status string
}
//HTTP GET /create
func (app *application) create(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.URL.Path, time.Now())
task := &Task{Name: fmt.Sprintf("Task #%d", rand.Int()%1000), Status: "pending"}
// -------- problem code here ----
// This line works and does not generate any 'context canceled' errors
//ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
// However, this linegenerates 'context canceled' errors under mild load
ctx, cancel := context.WithTimeout(r.Context(), 100*time.Second)
// -------- end -------
defer cancel()
err := app.insertTask(ctx, task)
if err != nil {
fmt.Println("insert error:", err)
return
}
fmt.Fprintf(w, "%+v", task)
}
func (app *application) insertTask(ctx context.Context, t *Task) error {
stmt := `INSERT INTO task (name, status) VALUES ($1, $2) RETURNING ID`
row := app.DB.QueryRow(ctx, stmt, t.Name, t.Status)
err := row.Scan(&t.ID)
if err != nil {
return err
}
return nil
}
func main() {
rand.Seed(time.Now().UnixNano())
db, err := pgxpool.Connect(context.Background(), "postgres://test:test123@localhost:5432/test")
if err != nil {
log.Fatal(err)
}
log.Println("db conn pool created")
stmt := `CREATE TABLE IF NOT EXISTS public.task (
id uuid NOT NULL DEFAULT gen_random_uuid(),
name text NULL,
status text NULL,
PRIMARY KEY (id)
); `
_, err = db.Exec(context.Background(), stmt)
if err != nil {
log.Fatal(err)
}
log.Println("task table created")
defer db.Close()
app := &application{
DB: db,
}
mux := http.NewServeMux()
mux.HandleFunc("/create", app.create)
log.Println("http server up at localhost:4444")
err = http.ListenAndServe(":4444", mux)
if err != nil {
log.Fatal(err)
}
}

TLDR:使用r.Context()在生产中工作良好,使用浏览器测试是一个问题。

HTTP请求有自己的上下文,当请求完成时上下文被取消。这是一个特性,而不是一个bug。开发人员希望使用它,并在请求被客户端中断或超时时优雅地关闭执行。例如,取消的请求可能意味着客户端永远不会看到响应(事务结果),开发人员可以决定回滚该事务。

在生产环境中,对于正常的设计/构建api,请求取消并不经常发生。通常,流由服务器控制,服务器在取消请求之前返回结果。多个客户机请求不会相互影响,因为它们有独立的go-routine和上下文。再一次,我们谈论的是正常设计/构建的应用程序的快乐路径。您的示例应用程序看起来不错,应该可以正常工作。

问题在于我们如何测试应用程序。我们使用浏览器并刷新单个浏览器会话,而不是创建多个独立的请求。我没有检查到底发生了什么,但假设浏览器终止现有的请求,以便在单击ctrl-R时运行一个新的请求。服务器看到请求终止,并将其作为上下文取消传递给代码。

尝试使用curl或其他创建独立请求的脚本/实用程序测试您的代码。我相信在这种情况下你不会看到取消。

相关内容

最新更新