Play Framework 2.6,Postgresql。 Jooq 作为数据库访问库。
运行测试时,我得到
org.postgresql.util.PSQLException: FATAL: sorry, too many clients already
这是一个提供 jooq 的 dsl 上下文的辅助类:
@Singleton
class Db @Inject() (val db: Database, system: ActorSystem) {
val databaseContext: ExecutionContext = system.dispatchers.lookup("contexts.database")
def query[A](block: DSLContext => A): Future[A] = Future {
db.withConnection { connection: Connection =>
val dsl = DSL.using(connection, SQLDialect.POSTGRES_9_4)
block(dsl)
}
}(databaseContext)
def withTransaction[A](block: DSLContext => A): Future[A] = Future {
db.withTransaction { connection: Connection =>
val dsl: DSLContext = DSL.using(connection, SQLDialect.POSTGRES_9_4)
block(dsl)
}
}(databaseContext)
}
我在这样的存储库中使用这个助手类:
db.query { dsl =>
val records = dsl
.selectFrom(USERS)
.where(...)
...
}
}
application.conf
db.default.driver="org.postgresql.Driver"
db.default.url="jdbc:postgresql://localhost/postgres?user=postgres"
...
contexts {
database {
executor = "thread-pool-executor"
throughput = 1
thread-pool-executor {
fixed-pool-size = 9
}
}
}
...
build.sbt
...
libraryDependencies += jdbc
libraryDependencies += "org.jooq" % "jooq" % "3.10.5"
libraryDependencies += "org.jooq" % "jooq-codegen-maven" % "3.10.5"
libraryDependencies += "org.jooq" % "jooq-meta" % "3.10.5"
libraryDependencies += "org.postgresql" % "postgresql" % "42.1.4"
...
以及我在任何情况下的所有测试的基本特征:
class BaseFeatureSpec extends FeatureSpec
with GivenWhenThen
with GuiceOneServerPerSuite
with Matchers
with WsScalaTestClient
with BeforeAndAfterEach
with MockitoSugar {
override def fakeApplication(): Application =
new GuiceApplicationBuilder()
.overrides(bind[EmailService].to(classOf[EmailServiceStub]))
.build()
def config: Configuration = fakeApplication().configuration
def actorSystem: ActorSystem = fakeApplication().actorSystem
val db: Db = app.injector.instanceOf[Db]
val wsClient: WSClient = app.injector.instanceOf[WSClient]
val myPublicAddress = s"localhost:$port"
private val injector = fakeApplication().injector
def truncateDbOnEachRun = true
override protected def beforeEach(): Unit = {
if (truncateDbOnEachRun) {
truncateDb
}
}
protected def truncateDb = {
await(db.withTransaction { dsl =>
... truncate all dbs...
})
}
}
我的 postgresql 实例的最大连接数是 100。
我注意到,在运行测试时,我看到池几乎在每次测试之前创建了多次:
[info] application - Creating Pool for datasource 'default'
[info] application - Creating Pool for datasource 'default'
[info] application - Creating Pool for datasource 'default'
[info] application - Creating Pool for datasource 'default'
在我收到太多连接
错误之后。
请帮忙。
最佳答案
看起来你使用了默认类型的调度器,尝试添加 type = PinnedDispatcher,它用于 io 类型的调度器,如下所示。
thread-pool-executor {
...
type = PinnedDispatcher
}
您可以从中找到详细信息 https://doc.akka.io/docs/akka/2.5/dispatchers.html
关于postgresql - Play Framework : "too many connections" database error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48938328/