Last active
August 29, 2015 14:10
-
-
Save mocyuto/a965565f1fea115539e1 to your computer and use it in GitHub Desktop.
slickでcommons-dbcpを使う場合の書き方
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 com.cyberz.foxapi.util | |
import javax.sql.DataSource | |
import com.typesafe.config.ConfigFactory | |
import org.apache.commons.dbcp.BasicDataSource | |
import scala.slick.jdbc.JdbcBackend.Database | |
/** | |
* @author Yuto Suzuki | |
*/ | |
object DB { | |
val config = ConfigFactory.load | |
val dbDriver = config.getString("db.driver") | |
// application.confに書かれているものを読み出す。 | |
lazy val hogePool = { | |
val conf = "db.hoge" | |
val ds = new BasicDataSource | |
applyConfig(ds, conf) | |
} | |
lazy val fugaPool = { | |
val conf = "db.fuga" | |
val ds = new BasicDataSource | |
applyConfig(ds, conf) | |
} | |
def applyConfig(ds: BasicDataSource, conf: String): BasicDataSource = { | |
val dbHost = config.getString(conf + ".host") | |
val dbPort = config.getInt(conf + ".port") | |
val dbName = config.getString(conf + ".name") | |
val dbUrl = s"jdbc:mysql://${dbHost}:${dbPort}/${dbName}?characterEncoding=UTF-8&TRACE_LEVEL_SYSTEM_OUT=2&zeroDateTimeBehavior=convertToNull" | |
ds.setDriverClassName(config.getString("db.driver")) | |
ds.setUsername(config.getString(conf + ".user")) | |
ds.setPassword(config.getString(conf + ".password")) | |
ds.setUrl(dbUrl) | |
ds.setMaxActive(config.getInt("db.max-active")) | |
ds.setMaxIdle(config.getInt("db.max-idle")) | |
ds.setMaxWait(config.getInt("db.max-wait")) | |
ds.setInitialSize(config.getInt("db.initial-size")) | |
ds.setValidationQuery(config.getString("db.validation-query")) | |
ds.setTestOnBorrow(config.getBoolean("db.test-on-borrow")) | |
ds.setTimeBetweenEvictionRunsMillis(config.getInt("db.time-between-evection-runs-mills")) | |
ds.setTestWhileIdle(config.getBoolean("db.test-while-idle")) | |
ds | |
} | |
} | |
trait DBConnection { | |
val dbSalt = DB.config.getString("db.salt") | |
// 以下のように複数DBにつなぐこともできる | |
val hogeDb = { | |
val ds = DB.hogePool | |
Database.forDataSource(ds) | |
} | |
val fugaDb = { | |
val ds = DB.fugaPool | |
Database.forDataSource(ds) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment