Вот одно из возможных решений.
Настройка базы данных
class Module(environment: Environment, configuration: Configuration) extends AbstractModule {
def configure(): Unit = {
bind(classOf[Config])
.annotatedWith(Names.named("dbConfig"))
.toInstance(configuration.underlying.getConfig("slick.dbs"))
bind(classOf[String])
.annotatedWith(Names.named("dbSchema1"))
.toInstance("default")
bind(classOf[String])
.annotatedWith(Names.named("dbSchema2"))
.toInstance("mydb2")
}
}
Создание класса помощника
@Named("databaseService")
@Singleton
class DatabaseService @Inject()(@Named("dbConfig") dbConfig: Config,
@Named("dbSchema1") schema1: String,
@Named("dbSchema2") schema2: String) extends Logging {
lazy val db1: JdbcBackend#DatabaseDef = {
info("Init DB1")
val database = DatabaseConfig.forConfig[MySQLProfile](schema1, dbConfig).db
info("DB1 is ready")
database
}
lazy val db2: JdbcBackend#DatabaseDef = {
info("Init DB2")
val database = DatabaseConfig.forConfig[MySQLProfile](schema2, dbConfig).db
info("DB2 is ready")
database
}
def run[R](action: DBIOAction[R, NoStream, Nothing])(implicit db: JdbcBackend#DatabaseDef): Future[R] = {
import scala.concurrent.ExecutionContext.Implicits.global
db.run(action).recoverWith {
case exception: Throwable => {
error("query failed", exception)
Future.failed[R](exception)
}
}
}
def runDb1[R](action: DBIOAction[R, NoStream, Nothing]): Future[R] = {
implicit val db = db1
run(action)
}
def runDb2[R](action: DBIOAction[R, NoStream, Nothing]): Future[R] = {
run(action)(db2)
}
}
Внедрение зависимости и выбор базы данных для запуска
@Singleton
class UserRepositoryImpl @Inject() (databaseService: DatabaseService)
(implicit ec: ExecutionContext) extends UserRepository {
def all(param: Param): EitherT[Future, String, Seq[User]] = EitherT {
val db = param match {
case db1 => databaseService.db1
case db2 => databaseService.db2
}
databaseService.run(UserTable.UserQuery.result.asTry)(db).map {
case Success(result) => {
logger.debug(s"all success: $result")
Right(result)
}
case Failure(error) => {
val str = s"all error: ${error.getMessage}"
logger.error(str, error)
Left(str)
}
}
}
}