首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用R的池包重新连接到PostgreSQL数据库

用R的池包重新连接到PostgreSQL数据库
EN

Stack Overflow用户
提问于 2019-03-04 18:00:12
回答 1查看 2K关注 0票数 9

我有一个用R 水管工构建的API,它使用RPostgreSQL池子连接到PostgreSQL数据库(尽管如果我使用的是一个闪亮的应用程序,这也适用):

代码语言:javascript
复制
# 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) })
)

我想每天导入新的数据。最简单的方法是创建一个新的数据库并将其推广到生产中:

代码语言:javascript
复制
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随后丢失的是到数据库的连接,并且不会自动尝试重新连接:

代码语言:javascript
复制
> 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.
)

即使我没有每天更换数据库,DB服务器偶尔也会重新启动,这也会导致我的应用程序崩溃。重新连接似乎不是池、RPostgreSQL或DBI的特性。有人知道解决这个问题的方法吗?

EN

回答 1

Stack Overflow用户

发布于 2020-02-01 07:00:04

我使用带有以下函数的普通DBI (没有池)始终为DBI调用提供活动连接(例如DBI::dbExistsTable(rdsConnect(),"mytable"))。

代码语言:javascript
复制
#' Connect returns a database connection.
#' Retrieves the connection parameters from configuration.
#' 
#' FIXME: dbIsValid is not implemented
#' https://github.com/tomoakin/RPostgreSQL/issues/76
#' workaround implemented with isPostgresqlIdCurrent()
#' @return rds allocated connection
rdsConnect <- function() {
  if (!((exists("rds") && (isPostgresqlIdCurrent(rds))))) {
    source('./config.R', local = TRUE)
    print("New PostgreSQL connection")
    rds <<- DBI::dbConnect(RPostgreSQL::PostgreSQL(),
      dbname = rds_params("rds_database"),
      host = rds_params("rds_host"),
      user = rds_params("rds_user"),
      password = rds_params("rds_password")
    )
  } else print("Valid PostgreSQL connection")
  return(rds)
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54988978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档