Skip to content

Instantly share code, notes, and snippets.

@dominics
Created July 31, 2018 22:02
Show Gist options
  • Save dominics/c9e052f32bddf0b0ea16ebdc073caab1 to your computer and use it in GitHub Desktop.
Save dominics/c9e052f32bddf0b0ea16ebdc073caab1 to your computer and use it in GitHub Desktop.
Custom AsyncExecutor for Database.forConfig
slick.dbs.default {
profile = "foo.bar.PostgresProfile$"
db {
poolName = "slick-default-db"
url = ${?DB_URL}
user = ${?DB_USER}
password = ${?DB_PASSWORD}
numThreads = 20
minConnections = 5
maxConnections = 20
}
}
package foo.bar
import java.sql.{ Array => _, _ }
import com.typesafe.config.{ Config, ConfigFactory }
import slick.jdbc.{ JdbcBackend, JdbcDataSource }
import slick.util.ConfigExtensionMethods._
import slick.util.{ AsyncExecutor, ClassLoaderUtil }
trait CustomExecutorJdbcBackend extends JdbcBackend {
override val Database = new DatabaseFactoryDef {}
trait DatabaseFactoryDef extends super.DatabaseFactoryDef {
override def forConfig(
path: String,
config: Config = ConfigFactory.load(),
driver: Driver = null,
classLoader: ClassLoader = ClassLoaderUtil.defaultClassLoader
): Database = {
val usedConfig: Config = if (path.isEmpty) config else config.getConfig(path)
val source = JdbcDataSource.forConfig(usedConfig, driver, path, classLoader)
val poolName = usedConfig.getStringOr("poolName", path)
val numThreads = usedConfig.getIntOr("numThreads", 20)
val maxConnections = source.maxConnections.fold(numThreads * 5)(identity)
val registerMbeans = usedConfig.getBooleanOr("registerMbeans", false)
// Use a custom async executor class:
val executor = SomeCustomAsyncExecutor(poolName, numThreads, numThreads, usedConfig.getIntOr("queueSize", 1000),
maxConnections, registerMbeans = registerMbeans)
forSource(source, executor)
}
}
}
object CustomExecutorJdbcBackend extends CustomExecutorJdbcBackend
package foo.bar
import com.github.tminglei.slickpg._
trait PostgresProfile extends ExPostgresProfile
with PgDateSupportJoda
with PgDate2Support
with PgArraySupport
with PgEnumSupport
with PgRangeSupport
with PgHStoreSupport {
// [...]
// other profile content, cusotmized API etc.
}
// Must use an early definitions block to set the backend
object PostgresProfile extends {
override val backend = CustomExecutorJdbcBackend
} with PostgresProfile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment