登录
首页 >  Golang >  Go问答

动态配置Golang Pgx连接池

来源:stackoverflow

时间:2024-02-18 08:03:36 167浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《动态配置Golang Pgx连接池》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我有一个带有 postgres 的 rds 实例,并且通过 iam 用户进行身份验证。密码是每 15 分钟刷新一次的令牌:

    authtoken, err := rdsutils.buildauthtoken(endpoint, "mars-east-4", "iamuser", envcredentials)
    if err != nil {
        return "", err
    }

但是,我已经看到连接池在令牌过期后抛出身份验证错误的问题,并且我没有找到任何好的方法。

我的想法是创建一个函数 getpool 并将其注入到我的存储库中,该函数将返回一个 pool 对象 pgxpool.pool

func (p pool) getpool() (*pgxpool.pool, error) {
    config, err := p.getconfig()
    if err != nil {
        return nil, err
    }

    pool, err := pgxpool.connectconfig(context.background(), config)
    if err != nil {
        return nil, err
    }

    return pool, nil
}

getconfig 内部将调用 buildauthtoken,但仅每 15 分钟调用一次(伪代码):

if time > 15minutes {
  return buildauthtoken()
}

因此,如果 15 分钟过去了,我将重新获取令牌,否则我将使用已有的令牌。 这将是最终的解决方案

func (p Pool) GetPool() (*pgxpool.Pool, error) {
    // Pseudocode
    if p.time < 15minutes {
      return p.Pool, nil
    }

    config, err := p.getConfig()
    if err != nil {
        return nil, err
    }

    pool, err := pgxpool.ConnectConfig(context.Background(), config)
    if err != nil {
        return nil, err
    }

    p.Pool = pool
    p.time = time.Now()
    return pool, nil
}

那么这种方法效率低下吗?有更好的方法吗?另外,由于我将在服务器中使用它,那么竞争条件怎么样? 谢谢


解决方案


最近 pgx 为 pgxpool.pool 引入了 beforeconnect 挂钩

这是我当前的解决方案

func (p *Pool) getConfig() (*pgxpool.Config, error) {
    config, err := pgxpool.ParseConfig("")
    if err != nil {
        return nil, err
    }

    /**
    This will refresh the password if the connection is expired
    */
    config.BeforeConnect = func(ctx context.Context, config *pgx.ConnConfig) error {
        if p.isTokenExpired() {
            creds, err := p.getCredentials()
            if err != nil {
                return err
            }

            config.User = creds.user
            config.Password = creds.password
            config.Host = creds.host
            config.Database = creds.database
            config.Port = creds.port
            p.cachedCredentials = creds
            p.expire = time.Now()
        } else {
            config.User = p.cachedCredentials.user
            config.Password = p.cachedCredentials.password
            config.Host = p.cachedCredentials.host
            config.Database = p.cachedCredentials.database
            config.Port = p.cachedCredentials.port
        }

        return nil
    }

    return config, nil
}

如果轮询需要创建新连接,它将首先调用 beforeconnect 挂钩,getcredentials 将从 aws iam 检索令牌,但这仅在令牌接近其过期时间(根据 aws 的规定为 15 分钟)时才会发生 p>

ps:该功能尚未发布,但已合并到master中。要使用它,您必须获得最新的提交

理论要掌握,实操不能落!以上关于《动态配置Golang Pgx连接池》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>