Slick2 사용 노트(5) 데이터 소스 구성

3132 단어 데이터 소스
본문iteye.com 절단 출처 밝혀주세요
 
Slick2는 내장형 Database(사용 시 해당 데이터베이스에 해당하는 패키지 가져오기
예를 들어 mysql은:import scala입니다.slick.driver.MySQLDriver.simple._) forURL 방법
그리고 forDriver는 직접 Driver를 통해 연결을 받습니다) 데이터베이스 연결을 받습니다.
Slick2는 forName(JNDI)와forConfig(설정을 통해)로도 얻을 수 있다
 
이 포는 포DataSource라는 방법입니다.
    /**
     * Create a Database based on a DataSource.
     */
    def forDataSource(ds: DataSource): DatabaseDef = new DatabaseDef {
      def createConnection(): Connection = ds.getConnection
    }

이 DataSource 클래스는 javax입니다.sql.DataSource 
 
 
여기서 간단하게 데이터 원본을 사용하는 방식을 알려드릴게요.
데이터 소스. 저는 아리의 Druid를 사용하는데 어떤 걸 쓰든 상관없어요. 취향을 보세요.
Spring xml 방식으로 데이터 Source를 설정하는 데 익숙한 학생들은 코드에 대한 설정이 낯설겠지만 사실 간단합니다.
구성 코드는 다음과 같습니다.
package infrastructure

import com.alibaba.druid.pool.DruidDataSource
import javax.sql.DataSource

sealed class DS(val config: DataSourceConfig) {
  private val dataSource = new DruidDataSource
  conf(config)

  def get: DataSource = {
    sync(!dataSource.isInited(), dataSource.init(), dataSource)
    dataSource
  }

  def close = {
    sync(dataSource.isInited(), dataSource.close(), dataSource)
  }

  private def sync(test: => Boolean, op: => Unit, lock: AnyRef) = {
    if (test)
      lock.synchronized {
        if (test) op
      }
  }

  private def conf(config: DataSourceConfig): Unit = {
    dataSource.setUrl(config.url)
    dataSource.setUsername(config.name)
    dataSource.setPassword(config.password)
    dataSource.setInitialSize(config.initSize)
    dataSource.setMinIdle(config.minIdle)
    dataSource.setMaxActive(config.maxActive)
    dataSource.setValidationQuery(config.validateQuery)
  }
}

object DS {
  val _lock = new Object
  val db = new DS(new MyDataSourceConfig)
  def apply() = {
    _lock.synchronized {
      db.get
    }
  }

  def apply(conf: DataSourceConfig) = {
    _lock.synchronized {
      db.conf(conf)
      db.dataSource.restart()
      db.get
    }
  }
}

trait DataSourceConfig {
  def url: String
  def name: String
  def password: String
  def initSize: Int = 1
  def minIdle: Int = 1
  def maxActive: Int
  def validateQuery = "select 'x'"
}

class MyDataSourceConfig extends DataSourceConfig {
  def url = "jdbc:mysql://localhost:3306/cqrs"
  def name = "root"
  def password = ""
  def maxActive = 10
}

 
상기 몇 개의 매개 변수에 관하여druid의 github를 참고할 수 있다.
 
사용도 간단합니다.
Database.forDataSource(DS()).withSession {
      implicit session =>
        q.list
}

 

좋은 웹페이지 즐겨찾기