我有一个使用 R管道工构建的 API,它使用RPostgreSQL和池连接到 PostgreSQL 数据库(尽管如果我使用的是 Shiny 应用程序,这也适用):
# create the connection pool
pool <- dbPool(
drv = PostgreSQL(),
host = Sys.getenv("DB_HOST"),
port = 5432,
dbname = "db",
user = Sys.getenv("DB_USER"),
password = Sys.getenv("DB_PASSWORD")
)
# start the API
pr <- plumb("plumber.R")
# on stop, close the pool
pr$registerHooks(
list("exit" = function() { poolClose(pool) })
)
我想每天导入新数据。最简单的方法是创建一个新数据库并将其推广到生产环境:
CREATE DATABASE db_new;
-- create the tables
-- bulk-insert the data
SELECT pg_terminate_backend (pid) FROM pg_stat_activity WHERE datname = 'db';
DROP DATABASE db;
ALTER DATABASE db_new RENAME TO db;
这是快速的,并且可以最大限度地减少停机时间。问题是pool
然后失去与数据库的连接并且不会自动尝试重新连接:
> tbl(pool, "users")
Error in postgresqlExecStatement(conn, statement, ...) :
RS-DBI driver: (could not Retrieve the result : FATAL: terminating connection due to administrator command
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
)
即使我不是每天都更换数据库,数据库服务器偶尔也会重新启动,这也会导致我的应用程序崩溃。重新连接似乎不是池、RPostgreSQL 或 DBI 的功能。有谁知道解决这个问题的方法?