У меня были похожие проблемы, чтобы заставить Play
работать с Postgres
.
Соединения с базой данных должны быть настроены с использованием пула из HikariCP
. Вставленная конфигурация, как следует из файла сборки, получает Slick
для использования HikariCP
.
Вот вы идете с моей базой и дайте мне знать, если она работает:
Содержание build.sbt
:
import com.typesafe.sbt.SbtScalariform._
import scalariform.formatter.preferences._
val SlickVersion = "3.3.2"
name := “play-slick"
version := "6.0.0"
//val PlayVersion = "2.8.5"
scalaVersion := "2.13.1"
resolvers += Resolver.jcenterRepo
resolvers += "Sonatype snapshots" at "https://oss.sonatype.org/content/repositories/snapshots/"
libraryDependencies ++= Seq(
jdbc,
"org.postgresql" % "postgresql" % "42.2.18",
"com.typesafe.slick" %% "slick-hikaricp" % SlickVersion,
"org.webjars" %% "webjars-play" % "2.8.0",
"org.webjars" % "bootstrap" % "4.4.1" exclude("org.webjars", "jquery"),
"org.webjars" % "jquery" % "3.2.1",
"net.codingwell" %% "scala-guice" % "4.2.6",
"com.iheart" %% "ficus" % "1.4.7",
"com.typesafe.play" %% "play-mailer" % "8.0.1",
"com.typesafe.play" %% "play-mailer-guice" % "8.0.1",
//"com.enragedginger" %% "akka-quartz-scheduler" % "1.8.2-akka-2.6.x",
"com.enragedginger" %% "akka-quartz-scheduler" % "1.8.3-akka-2.6.x",
"com.adrianhurt" %% "play-bootstrap" % "1.5.1-P27-B4",
specs2 % Test,
ehcache,
guice,
jdbc,
filters
)
lazy val root = (project in file(".")).enablePlugins(PlayScala)
routesImport += "utils.route.Binders._"
// https://github.com/playframework/twirl/issues/105
TwirlKeys.templateImports := Seq()
scalacOptions ++= Seq(
"-deprecation", // Emit warning and location for usages of deprecated APIs.
"-feature", // Emit warning and location for usages of features that should be imported explicitly.
"-unchecked", // Enable additional warnings where generated code depends on assumptions.
"-Xfatal-warnings", // Fail the compilation if there are any warnings.
//"-Xlint", // Enable recommended additional warnings.
"-Ywarn-dead-code", // Warn when dead code is identified.
"-Ywarn-numeric-widen", // Warn when numerics are widened.
// Play has a lot of issues with unused imports and unsued params
// https://github.com/playframework/playframework/issues/6690
// https://github.com/playframework/twirl/issues/105
"-Xlint:-unused,_"
)
//********************************************************
// Scalariform settings
//********************************************************
scalariformAutoformat := true
ScalariformKeys.preferences := ScalariformKeys.preferences.value
.setPreference(FormatXml, false)
.setPreference(DoubleIndentConstructorArguments, false)
.setPreference(DanglingCloseParenthesis, Preserve)
Конфигурация базы данных, которую следует добавить в application.conf
, при условии, что Postgres
настроено на использование зашифрованного соединения. Я использовал letsencrypt
.
#include "database.conf"
db.default.driver=org.postgresql.Driver
db.default.url="jdbc:postgresql://localhost/users_db?ssl=true&sslmode=require"
db.default.username=${?DATABASE_USER}
db.default.password=${?DATABASE_PASSWORD}
db.default.hikaricp.connectionTestQuery = "SELECT 1"
fixedConnectionPool = 5
database.dispatcher {
executor = "thread-pool-executor"
throughput = 1
thread-pool-executor {
fixed-pool-size = ${fixedConnectionPool}
}
}
Образец из UserDAOImpl
для подписи и импорта:
package models.daos
import java.util.UUID
import javax.inject.Inject
import models.User
import play.api.db.Database
import scala.concurrent.{ ExecutionContext, Future }
import scala.util.{ Failure, Success }
/**
* Give access to the user object.
*/
class UserDAOImpl @Inject() (db: Database)(implicit executionContext: DatabaseExecutionContext) extends UserDAO {
/**
* Finds a user by its user info.
*
* @param userInfo The user info of the user to find.
* @return The found user or None if no user for the given user info could be found.
*/
def find(userInfo: UserInfo) =
Future {
val c = db.getConnection()
val statement = c.prepareStatement("SELECT * FROM users WHERE email = ?;")
statement.setString(1, userInfo.email)
if (statement.execute()) {
val resultSet = statement.getResultSet
if (resultSet.next()) {
val userID = resultSet.getString("userid")
val firstName = resultSet.getString("firstName")
val lastName = resultSet.getString("lastName")
val affiliation = resultSet.getString("affiliation")
val roleTitle = resultSet.getString("roleTitle")
val fullName = resultSet.getString("fullName")
val email = resultSet.getString("email")
val avatarURL = resultSet.getString("avatarURL")
val activatedStr = resultSet.getString("activated")
val activated: Boolean = activatedStr match {
case "f" => false
case "t" => true
case _ => false
}
statement.close()
c.close()
Some(
User(
UUID.fromString(userID),
firstName = Some(firstName),
lastName = Some(lastName),
affiliation = Some(affiliation),
roleTitle = Some(roleTitle),
fullName = Some(fullName),
email = Some(email),
avatarURL = Some(avatarURL),
activated))
} else {
statement.close()
c.close()
None
}
} else {
statement.close()
c.close()
None
}
}
}
Поместите этот файл DatabaseExecutionContext
в тот же каталог, что и ваши файлы dao
.
package models.daos
import javax.inject._
import akka.actor.ActorSystem
import play.api.libs.concurrent.CustomExecutionContext
/**
* This class is a pointer to an execution context configured to point to "database.dispatcher"
* in the "application.conf" file.
*/
@Singleton
class DatabaseExecutionContext @Inject() (system: ActorSystem) extends CustomExecutionContext(system, "database.dispatcher")
person
James
schedule
23.05.2021