Created
April 8, 2016 09:03
-
-
Save tototoshi/15c012fe9bb73164607c2723febcb41b to your computer and use it in GitHub Desktop.
scalikejdbc+play2.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package models | |
import javax.inject.{Inject, Provider, Singleton} | |
import play.api.inject.{ApplicationLifecycle, Binding, Module} | |
import play.api.{Configuration, Environment, Logger} | |
import scalikejdbc.config.TypesafeConfigReader | |
import scalikejdbc.{Commons2ConnectionPoolFactory, ConnectionPool} | |
import scala.concurrent.{ExecutionContext, Future} | |
class ConnectionPoolProvider extends Provider[ConnectionPool] { | |
private val logger = Logger(classOf[ConnectionPoolProvider]) | |
override def get(): ConnectionPool = { | |
val jdbc = TypesafeConfigReader.readJDBCSettings() | |
logger.info("Preparing connection pool...") | |
Commons2ConnectionPoolFactory(jdbc.url, jdbc.user, jdbc.password) | |
} | |
} | |
@Singleton | |
class ConnectionPoolShutdown @Inject() (lifecycle: ApplicationLifecycle, | |
connectionPool: ConnectionPool, executionContext: ExecutionContext) { | |
private val logger = Logger(classOf[ConnectionPoolShutdown]) | |
lifecycle.addStopHook(() => Future { | |
logger.info("Shutdown connection pool") | |
connectionPool.close() | |
}(executionContext)) | |
} | |
class ConnectionPoolModule extends Module { | |
override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq( | |
bind[ConnectionPool].toProvider[ConnectionPoolProvider].eagerly(), | |
bind[ConnectionPoolShutdown].toSelf.eagerly() | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment