doujianjian2060 2019-06-03 04:35
浏览 561

PostgreSQL函数pg_ping()的目的是什么?

According to the manual ( https://php.net/pg_ping ):

pg_ping() pings a database connection and tries to reconnect it if it is broken.

Aaaalright... So where would one ever do that? Is this for many-hours-long while (1) loops which only very rarely makes a query? How long is the timeout normally? Why is there a timeout at all? Should I change some setting? I don't understand the purpose of this feature/function. I can't find any sensible example or explanation as to when it would ever be used, or why.

Please explain.

  • 写回答

1条回答 默认 最新

  • duanhe2027 2019-06-03 06:35
    关注

    First, a factual answer:

    The function is there to test if the connection is still active. The intention is to test a connection that could have been idle for a while, for example one that you just grabbed from a connection pool.

    The intention is to minimize the risk of failure during an immediately following database request.

    An opinionated answer:

    This concept is ill-advised, and your feeling that there is something wrong with it is justified.

    There are two problems:

    1. A race condition. Even if it ia not likely, the connection can still go bad between the time you test it and the time you use it.

      So if you want to write robust code, you still have to make provisions for connection failure in the cide that uses the database connection (retry, not let the error propagate to the user immediately, ...)

    2. In the likely case that the connection is still fine, you incur the unnecessary cost of a client-server round trip, a cost that you will have to pay for every database request.

      Therefore, it is better to follow the principle of “try first, apologize later”: don't uae functions like this. Rather, proceed with the database request you actually intend to do, catch any errors, and if there are errors that indicate a broken connection, re-establish it and retry. Your code will become simpler and more robust.

    I wouldn't set any timeouts on database connections at all. Rather, use a connection pool that manages that for you. It will keep some connections around in anticipation of database activity and close extra connections after a certain idle time.

    评论

报告相同问题?

悬赏问题

  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致
  • ¥15 禅道二次开发编辑版本,上传不了发行包
  • ¥30 arcgis处理夜间灯光数据,使用投影栅格使图像变暗
  • ¥15 荔枝派Zero开发板登陆后怎么自动执行可执行文件
  • ¥15 复现:how to backdoor federated learning
  • ¥15 vue进度条切换,带有背景边框
  • ¥15 安防监控网络故障问题