我有以下代码用于连接到 Postgres 数据库:
func connectToPostgres(ctx context.Context, url string) (*pgxpool.Pool, error) {
var err error
for i := 0; i < 5; i++ {
p, err := pgxpool.Connect(ctx, url)
if err != nil || p == nil {
time.Sleep(3 * time.Second)
continue
}
log.Printf("pool returned from connect: %s", p)
return p, nil
}
return nil, errors.Wrap(err, "timed out waiting to connect postgres")
}
用例是在使用 docker-compose 启动我的服务器时等待 Postgres 可用。即使代码休眠 if p == nil
,第一次返回之前的日志也会打印出来:pool returned from connect: %!s(*pgxpool.Pool=<nil>)
有什么方法pgxpool
可以让后台进程实现p == nil
吗?
关于为什么会发生这种情况的任何想法?
编辑:这似乎只发生在通过 docker-compose 运行我的应用程序和 Postgres 时。我正在使用以下撰写文件:
services:
app:
build: .
ports:
- "8080:8080"
depends_on:
- "db"
db:
image: postgres
restart: always
environment:
- POSTGRES_DB=demo_db
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
ports:
- "8081:5432"
和我的应用程序的 Dockerfile:
FROM golang:1.17
WORKDIR /
COPY go.mod .
COPY go.sum .
COPY *.go .
RUN go mod download
RUN go build
EXPOSE 8080
CMD [ "./app" ]
还有一个最小可重现的示例 go 文件:
package main
import (
"context"
"fmt"
"log"
"net/http"
"time"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/pkg/errors"
)
func main() {
log.Printf("connecting to postgres...")
pgpool, err := connectToPostgres(context.Background(), "postgresql://localhost:5432/demo_db")
log.Printf("pool: %s", pgpool)
if err != nil {
log.Fatalln(err)
}
log.Printf("successfully connected to postgres")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
log.Println("stopped")
}
func connectToPostgres(ctx context.Context, url string) (*pgxpool.Pool, error) {
var err error
for i := 0; i < 5; i++ {
p, err := pgxpool.Connect(ctx, url)
if err != nil || p == nil {
time.Sleep(3 * time.Second)
continue
}
log.Printf("pool returned from connect: %s", p)
return p, nil
}
return nil, errors.Wrap(err, "timed out waiting to connect postgres")
}