当前位置: 首页>>代码示例>>Scala>>正文


Scala DataSource类代码示例

本文整理汇总了Scala中javax.sql.DataSource的典型用法代码示例。如果您正苦于以下问题:Scala DataSource类的具体用法?Scala DataSource怎么用?Scala DataSource使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了DataSource类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: dataSource

//设置package包名称以及导入依赖的类
package teksol

import java.util.Locale
import javax.sql.DataSource

import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.datasource.DataSourceTransactionManager
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.support.TransactionTemplate
import teksol.infrastructure.{EventBus, InMemoryI18n}
import teksol.mybank.domain.services.MyBankAppService
import teksol.mybank.infrastructure.postgres.PostgresMyBankRepository
import teksol.postgres.{PostgresEventBus, PostgresFamilyApp}

trait Config {
    def dataSource: DataSource

    lazy val jdbcTemplate: JdbcTemplate = new JdbcTemplate(dataSource)

    lazy val transactionManager: PlatformTransactionManager = new DataSourceTransactionManager(dataSource)
    lazy val transactionTemplate: TransactionTemplate = new TransactionTemplate(transactionManager)

    lazy val eventBus: EventBus = new PostgresEventBus(jdbcTemplate)
    lazy val app = new PostgresFamilyApp(jdbcTemplate, eventBus)
    lazy val myBankRepository = new PostgresMyBankRepository(jdbcTemplate, eventBus)
    lazy val myBankService = {
        val service = new MyBankAppService(myBankRepository, eventBus)
        eventBus.register(service)
        service
    }

    val en_US = Locale.US
    val fr_CA = Locale.CANADA_FRENCH
    val fr_FR = Locale.FRANCE

    lazy val i18n = new InMemoryI18n(Map(
        en_US -> Map(
            "salary.none" -> "No completed chores this period",
            "salary.positive" -> "%{numUnitsCompleted} completed this week",
            "salary.negative" -> "%{numUnitsCompleted} completed this week",
            "interests.none" -> "No interests for period",
            "interests.negative" -> "Negative interests on $ %{balance} balance, at a rate of %{rate}",
            "interests.positive" -> "Interests on $ %{balance} balance, at a rate of %{rate}"),
        fr_CA -> Map(
            "salary.none" -> "Aucune tâche ménagères complétées cette semaine",
            "salary.positive" -> "%{numUnitsCompleted} tâches ménagères complétées cette semaine",
            "salary.negative" -> "%{numUnitsCompleted} tâches ménagères complétées cette semaine",
            "interests.none" -> "Aucun intérêts pour la période",
            "interests.negative" -> "Intérêts négatifs calculés sur un solde de %{balance} $ et un taux de %{rate}",
            "interests.positive" -> "Intérêts calculés sur un solde de %{balance} $ et un taux de %{rate}"),
        fr_FR -> Map(
            "salary.none" -> "Aucune tâche ménagères complétées cette semaine",
            "salary.positive" -> "%{numUnitsCompleted} tâches ménagères complétées cette semaine",
            "salary.negative" -> "%{numUnitsCompleted} tâches ménagères complétées cette semaine",
            "interests.none" -> "Aucun intérêts pour la période",
            "interests.negative" -> "Intérêts négatifs calculés sur un solde de %{balance} $ et un taux de %{rate}",
            "interests.positive" -> "Intérêts calculés sur un solde de %{balance} $ et un taux de %{rate}")))
} 
开发者ID:francois,项目名称:family,代码行数:59,代码来源:Config.scala

示例2: DbDriversBuilder

//设置package包名称以及导入依赖的类
package com.criteo.qwebmon.drivers

import java.util.Properties
import javax.sql.DataSource

import com.criteo.qwebmon.DbDriver
import com.mchange.v2.c3p0.ComboPooledDataSource
import com.typesafe.config.{Config, ConfigObject, ConfigValueType}

import scala.collection.JavaConverters._

class DbDriversBuilder(config: Config) {

  val dbDrivers: Map[String, DbDriver] = config.getObject("targets")
    .entrySet().asScala
    .foldLeft(Map.empty[String, DbDriver]) { case (acc, entry) =>

    val targetName = entry.getKey
    val targetConfig = entry.getValue match {
      case c if c.valueType() == ConfigValueType.OBJECT => c.asInstanceOf[ConfigObject].toConfig
      case x => sys.error(s"illegal config syntax at $x")
    }

    targetConfig.getString("driver") match {
      case "fake-db" => acc + (targetName -> new FakeDbDriver(targetName))
      case "mysql" => acc + (targetName -> new MysqlDbDriver(targetName, buildDataSource(targetConfig)))
      case "vertica" => acc + (targetName -> new VerticaDbDriver(targetName, buildDataSource(targetConfig)))
      case x => sys.error(s"unknown driver supplied: $x, for target named: $targetName, with config: $targetConfig")
    }
  }

  private def buildDataSource(config: Config): DataSource = {
    val dataSource = new ComboPooledDataSource()

    if (config.hasPath("properties")) {
      val connectionProps = new Properties()
      config.getConfig("properties").entrySet().asScala.foreach { entry =>
        val key = entry.getKey
        val value = entry.getValue.unwrapped().toString

        connectionProps.setProperty(key, value)
      }
      dataSource.setProperties(connectionProps)
    }

    dataSource.setJdbcUrl(config.getString("url"))
    dataSource.setUser(config.getString("user"))
    dataSource.setPassword(config.getString("password"))

    dataSource
  }
} 
开发者ID:jqcoffey,项目名称:qwebmon,代码行数:53,代码来源:DbDriversBuilder.scala

示例3: MysqlDbDriver

//设置package包名称以及导入依赖的类
package com.criteo.qwebmon.drivers

import javax.sql.DataSource

import com.criteo.qwebmon.{RunningQuery, DbDriver}

import scala.collection.mutable

class MysqlDbDriver(val name: String, dataSource: DataSource) extends DbDriver {

  private val runningQueriesSql = "show processlist"

  override def runningQueries: Seq[RunningQuery] = {
    val runningQueries: Seq[RunningQuery] = JdbcHelpers.executeQuery(dataSource, runningQueriesSql) { rs =>
      val acc = mutable.ListBuffer.empty[RunningQuery]
      while (rs.next()) {
        Option(rs.getString(8)).foreach { query =>
          acc += RunningQuery(
            user = rs.getString(2),
            runSeconds = rs.getInt(6),
            query = query,
            hostname = rs.getString(3)
          )
        }
      }
      acc
    }
    runningQueries
  }

} 
开发者ID:jqcoffey,项目名称:qwebmon,代码行数:32,代码来源:MysqlDbDriver.scala

示例4: VerticaDbDriver

//设置package包名称以及导入依赖的类
package com.criteo.qwebmon.drivers

import javax.sql.DataSource

import com.criteo.qwebmon.{RunningQuery, DbDriver}

import scala.collection.mutable

class VerticaDbDriver(val name: String, dataSource: DataSource) extends DbDriver {

  private val runningQueriesSql =
    """
      |SELECT
      |  user_name as user_name,
      |  DATEDIFF('second', statement_start, clock_timestamp()) as exec_time,
      |  current_statement as current_statement,
      |  client_hostname as client_hostname
      |FROM
      |  sessions
      |WHERE
      |  transaction_id <> -1 and
      |  statement_id is not null
      |ORDER BY
      |  exec_time desc
    """.stripMargin

  override def runningQueries: Seq[RunningQuery] = {
    val runningQueries: Seq[RunningQuery] = JdbcHelpers.executeQuery(dataSource, runningQueriesSql) { rs =>
      val acc = mutable.ListBuffer.empty[RunningQuery]
      while (rs.next()) {
        acc += RunningQuery(
          user = rs.getString(1),
          runSeconds = rs.getInt(2),
          query = rs.getString(3),
          hostname = rs.getString(4)
        )
      }
      acc
    }
    runningQueries
  }

} 
开发者ID:jqcoffey,项目名称:qwebmon,代码行数:44,代码来源:VerticaDbDriver.scala

示例5: AppLoader

//设置package包名称以及导入依赖的类
import java.io.Closeable
import javax.sql.DataSource

import controllers.UsersController
import io.getquill._
import play.api.ApplicationLoader.Context
import play.api._
import play.api.db.evolutions.Evolutions
import play.api.db.{DBComponents, HikariCPComponents}
import play.api.inject.{Injector, NewInstanceInjector, SimpleInjector}
import play.api.routing.Router
import play.api.routing.sird._
import models.{Users}

class AppLoader extends ApplicationLoader {
  override def load(context: Context): Application = new BuiltInComponentsFromContext(context) with DBComponents with HikariCPComponents {

    lazy val db = new H2JdbcContext[SnakeCase](dbApi.database("default").dataSource.asInstanceOf[DataSource with Closeable])


    lazy val users = new Users(db)
    lazy val usersController = new UsersController(users)

    val router = Router.from {
      case GET(p"/users/${long(id)}")    => usersController.get(id)
      case POST(p"/users")               => usersController.create
      case DELETE(p"/users/${long(id)}") => usersController.delete(id)
      case PUT(p"/users/${long(id)}")    => usersController.update(id)
    }

    override lazy val injector: Injector =
      new SimpleInjector(NewInstanceInjector) + users + router + cookieSigner + csrfTokenSigner + httpConfiguration + tempFileCreator + global

    Evolutions.applyEvolutions(dbApi.database("default"))

  }.application
} 
开发者ID:getquill,项目名称:play-quill-jdbc,代码行数:38,代码来源:AppLoader.scala

示例6: cx

//设置package包名称以及导入依赖的类
package org.blinkmob

import java.sql.Connection
import javax.sql.DataSource

import resource._

import scala.util.control.ControlThrowable
import scala.util.{Failure, Success, Try}



trait CxProvider{ this:hasDataSource =>

  def cx[A](block: Connection => A): A = managed(ds.getConnection()).acquireAndGet(block(_))

  def tx[A](block: Connection => A): A ={
    cx { c =>
      c.setAutoCommit(false)
      Try({
        val r = block(c)
        c.commit()
        r
      }) match{
        case Success(r) => r
        case Failure(f) => {
          f match{
            case e: ControlThrowable => c.commit(); throw e
            case e => c.rollback(); throw e
          }
        }
      }


    }
  }

  def rbtx[A](block: Connection => A): A ={
    cx { c =>
      c.setAutoCommit(false)
      Try(block(c)) match{
        case Success(r) => c.rollback(); r
        case Failure(f) => c.rollback(); throw f
      }
    }
  }

} 
开发者ID:gnomff,项目名称:scala-tx-provider,代码行数:49,代码来源:CxProvider.scala

示例7: AppLoader

//设置package包名称以及导入依赖的类
import java.io.Closeable
import javax.sql.DataSource

import controllers.MainController
import io.getquill._
import models.Services
import unus.db._
import unus.helpers.Conf
import unus.model.FeatureBuilder
import unus.stage.{BlockerCacher, DatabaseBackup, PatientCacher, PatientDatabase}
import org.flywaydb.play.FlywayPlayComponents
import play.api.ApplicationLoader.Context
import play.api._
import play.api.db.{DBComponents, HikariCPComponents}
import play.api.inject.{Injector, NewInstanceInjector, SimpleInjector}
import play.api.routing.Router
import play.filters.csrf._
import router.Routes

class AppLoader extends ApplicationLoader {
  override def load(context: Context): Application = new BuiltInComponentsFromContext(context)
    with DBComponents with HikariCPComponents  with CSRFComponents
    with FlywayPlayComponents with play.filters.HttpFiltersComponents with _root_.controllers.AssetsComponents {

    lazy val db = new PostgresJdbcContext[PostgresEscape](dbApi.database("default").dataSource.asInstanceOf[DataSource with Closeable])

    lazy val services = new Services(db)
    lazy val patientCacher = new PatientCacher
    lazy val repo = new Repository(db)
    lazy val blockerCachers = Conf.blockers.map(new BlockerCacher(repo, patientCacher.value, _))
    lazy val features =  Conf.features
    lazy val controller = new MainController(services, repo, patientCacher, blockerCachers, features)(controllerComponents)

    lazy val router: Router = new Routes(httpErrorHandler, controller)

    

    override lazy val injector: Injector =
      new SimpleInjector(NewInstanceInjector) + cookieSigner + csrfTokenSigner + httpConfiguration + tempFileCreator + router

    override lazy val httpFilters = Seq(csrfFilter)

    flywayPlayInitializer

    new PatientDatabase(repo, patientCacher).run()

    if(services.getLabelCount == 0) {
      new DatabaseBackup[Label]("Label").load()
    }

    if(services.getBlockedRowCount == 0) {
      new DatabaseBackup[BlockedRow]("BlockedRow").load()
    }

  }.application
} 
开发者ID:mindfulmachines,项目名称:unus,代码行数:57,代码来源:AppLoader.scala

示例8: initFlyway

//设置package包名称以及导入依赖的类
package im.actor.server.db

import java.sql.Connection
import javax.sql.DataSource

import org.flywaydb.core.Flyway
import org.flywaydb.core.api.MigrationInfo
import org.flywaydb.core.api.callback.FlywayCallback

trait FlywayInit {
  def initFlyway(ds: DataSource) = {
    val flyway = new Flyway()
    flyway.setDataSource(ds)
    flyway.setLocations("sql.migration")
    flyway.setCallbacks(new BeforeCleanCallback())
    flyway.setBaselineOnMigrate(true)
    //??????.sql?????????????.sql???
    //by Lining 2016/7/27
    flyway.setValidateOnMigrate(false)
    flyway
  }
}

class BeforeCleanCallback extends FlywayCallback {
  def afterBaseline(connection: Connection): Unit = {}
  def afterClean(connection: Connection): Unit = {}
  def afterEachMigrate(connection: Connection): Unit = {}
  def afterInfo(connection: Connection): Unit = {}
  def afterEachMigrate(connection: Connection, migrationInfo: MigrationInfo): Unit = {}
  def afterMigrate(connection: Connection): Unit = {}
  def afterRepair(connection: Connection): Unit = {}
  def afterValidate(connection: Connection): Unit = {}
  def beforeBaseline(connection: Connection): Unit = {}
  def beforeClean(connection: Connection): Unit = executeStmt(connection, """DROP EXTENSION IF EXISTS "ltree" CASCADE;""")
  def beforeEachMigrate(connection: Connection, migrationInfo: MigrationInfo): Unit = {}
  def beforeInfo(connection: Connection): Unit = {}
  def beforeInit(connection: Connection): Unit = {}
  def beforeMigrate(connection: Connection): Unit = {}
  def beforeRepair(connection: Connection): Unit = {}
  def beforeValidate(connection: Connection): Unit = {}
  def afterInit(connection: Connection): Unit = executeStmt(connection, """DROP EXTENSION IF EXISTS "ltree" CASCADE;""")

  def executeStmt(connection: Connection, statement: String): Unit = {
    if (connection.getMetaData().getDriverName().startsWith("PostgreSQL")) {
      val stmt = connection.prepareStatement(statement)
      try {
        stmt.execute()
      } finally {
        stmt.close()
      }
    }
  }

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:55,代码来源:FlywayInit.scala

示例9: ScalaDomaConfig

//设置package包名称以及导入依赖的类
package domala

import javax.sql.DataSource

import org.seasar.doma.SingletonConfig
import org.seasar.doma.jdbc.Config
import org.seasar.doma.jdbc.Naming
import org.seasar.doma.jdbc.dialect._
import org.seasar.doma.jdbc.tx._

object ScalaDomaConfig {
  private var CONFIG: Option[ScalaDomaConfig] = None
  def initialize(
    dataSource: DataSource,
    dialect: Dialect = new H2Dialect,
    naming: Naming = Naming.NONE) = {
    CONFIG = Some(new ScalaDomaConfig(dataSource, dialect, naming))
  }
  def singleton = CONFIG.getOrElse(throw new RuntimeException("ScalaDomaConfig is not initialized."))
}

@SingletonConfig
class ScalaDomaConfig private (ds: DataSource, dialect: Dialect, naming: Naming) extends Config {

  getSqlFileRepository.clearCache

  val dataSource = ds match {
    case _: LocalTransactionDataSource => ds.asInstanceOf[LocalTransactionDataSource]
    case _ => new LocalTransactionDataSource(ds)
  }
  val transactionManager = new LocalTransactionManager(dataSource.getLocalTransaction(getJdbcLogger))

  override def getDataSource = dataSource
  override def getDialect = dialect
  override def getTransactionManager = transactionManager
  override def getNaming = naming

} 
开发者ID:bakenezumi,项目名称:scala-doma-sample,代码行数:39,代码来源:ScalaDomaConfig.scala

示例10: DBUtil

//设置package包名称以及导入依赖的类
package us.illyohs.bansdb.util

import javax.sql.DataSource
import java.sql.Connection
import java.sql.SQLException
import java.sql.Statement
import java.util.UUID

import org.spongepowered.api.Sponge
import org.spongepowered.api.service.sql.SqlService
import us.illyohs.bansdb.util.ConfigUtil._


object DBUtil {
  private var sqlServ: SqlService = null
  private var ds: DataSource = null

  def execute(execute: String): Unit = {
    sqlServ = Sponge.getServiceManager.provide(classOf[SqlService]).get()
    val URL: String = "jdbc:mysql://" + getURL + ":" + getPort + "/" + "?user=" + getUsername + "&password=" + getPass
    try {
      ds = sqlServ.getDataSource(URL)
      val connection: Connection = ds.getConnection
      val statement: Statement = connection.createStatement
      statement.execute(execute)
      statement.close
      connection.close
    }
    catch {
      case e: SQLException => e.printStackTrace
    }
  }

  def init: Unit = {
    execute("CREATE TABLE IF NOT EXISTS WARN_DB (warnee TEXT, sender TEXT, warnings SMALLINT, reason TEXT)")
    execute("CREATE TABLE IF NOT EXISTS BAN_DB (banee TEXT, sender TEXT, reason)")
  }


  def getWarning: Int = {
    null
  }

  def isPlayerBanned(uUID: UUID): Boolean = {
    return false
  }

  def isPlayerMuted(): Boolean = {
    return false
  }
} 
开发者ID:DragonTechMC,项目名称:BansDB,代码行数:52,代码来源:DBUtil.scala

示例11: DBConfig

//设置package包名称以及导入依赖的类
package com.github.swwjf.config

import javax.persistence.EntityManagerFactory
import javax.sql.DataSource

import org.apache.commons.dbcp2.BasicDataSource
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties
import org.springframework.boot.context.properties.{ConfigurationProperties, EnableConfigurationProperties}
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder
import org.springframework.context.annotation.{Bean, Configuration, Primary}
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
import org.springframework.orm.jpa.{JpaTransactionManager, LocalContainerEntityManagerFactoryBean}
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.annotation.EnableTransactionManagement

@Configuration
@EnableJpaRepositories(basePackages = Array(DBConfig.RootPackage))
@EnableTransactionManagement
@EnableConfigurationProperties(Array(classOf[JpaProperties]))
private class DBConfig {
  @Bean
  @ConfigurationProperties(prefix = "jdbc.datasource.ws")
  @Primary
  def wsDataSource(): DataSource =
    DataSourceBuilder
      .create()
      .`type`(classOf[BasicDataSource])
      .build()

  @Bean
  @Autowired
  def entityManagerFactory(builder: EntityManagerFactoryBuilder): LocalContainerEntityManagerFactoryBean =
    builder
      .dataSource(wsDataSource())
      .persistenceUnit("ws")
      .packages(DBConfig.RootPackage)
      .build()

  @Bean
  def transactionManager(entityManagerFactory: EntityManagerFactory): PlatformTransactionManager = {
    val txManager = new JpaTransactionManager()
    txManager.setEntityManagerFactory(entityManagerFactory)
    txManager
  }
}

private object DBConfig extends DBConstants

private sealed trait DBConstants {
  final val RootPackage = "com.github.swwjf"
} 
开发者ID:andrei-l,项目名称:scala-webapp-with-java-frameworks,代码行数:54,代码来源:DBConfig.scala

示例12: WSDBTestConfig

//设置package包名称以及导入依赖的类
package com.github.swwjf.config

import javax.sql.DataSource

import com.github.springtestdbunit.bean.{DatabaseConfigBean, DatabaseDataSourceConnectionFactoryBean}
import org.dbunit.database.DatabaseDataSourceConnection
import org.dbunit.ext.h2.H2DataTypeFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.{Bean, Configuration}

@Configuration
private class WSDBTestConfig {
  @Bean
  def databaseConfig(): DatabaseConfigBean = {
    val dbConfig = new DatabaseConfigBean()
    dbConfig.setDatatypeFactory(new H2DataTypeFactory())
    dbConfig
  }

  @Bean
  @Autowired
  def wsDBUnitDatabaseConnection(dataSource: DataSource, databaseConfigBean: DatabaseConfigBean): DatabaseDataSourceConnection = {
    val connectionFactoryBean: DatabaseDataSourceConnectionFactoryBean = new DatabaseDataSourceConnectionFactoryBean
    connectionFactoryBean.setDataSource(dataSource)
    connectionFactoryBean.setDatabaseConfig(databaseConfigBean)
    connectionFactoryBean.getObject
  }
}

private[swwjf] object WSDBTestConfig {
  final val ConnectionName = "wsDBUnitDatabaseConnection"
} 
开发者ID:andrei-l,项目名称:scala-webapp-with-java-frameworks,代码行数:33,代码来源:WSDBTestConfig.scala

示例13: MySQLFactory

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.commons.factories

import java.util.Properties
import javax.sql.DataSource

import com.flipkart.connekt.commons.connections.TConnectionProvider
import com.typesafe.config.Config
import org.springframework.jdbc.core.JdbcTemplate

class MySQLFactory private(config: Properties, connProvider: TConnectionProvider) extends TMySQLFactory {

  private val source: DataSource = connProvider.createDatasourceConnection(config)

  def this(host: String, database: String, username: String, password: String, poolProps: Config, connProvider: TConnectionProvider) = {
    this(PropsHelper.getConnProperties(host, database, username, password, poolProps), connProvider)
  }


  override def getJDBCInterface: JdbcTemplate = new JdbcTemplate(source)
}

object PropsHelper {
  val connUrl = "jdbc:mysql://%s/%s?autoReconnect=true&useUnicode=true&characterEncoding=utf-8"
  val driverClassName = "com.mysql.jdbc.Driver"

  def getConnProperties(host: String, database: String, username: String, password: String, poolProps: Config): Properties = {
    val connProps = new Properties()
    connProps.setProperty("url", connUrl.format(host, database))
    connProps.setProperty("driverClassName", driverClassName)
    connProps.setProperty("username", username)
    connProps.setProperty("password", password)
    connProps.setProperty("maxIdle", poolProps.getString("maxIdle"))
    connProps.setProperty("initialSize", poolProps.getString("initialSize"))
    connProps.setProperty("maxActive", poolProps.getString("maxActive"))
    connProps.setProperty("autoReconnect", "true")
    connProps.setProperty("testOnBorrow", "true")
    connProps.setProperty("testOnReturn", "false")
    connProps.setProperty("validationQuery", "select 1")
    connProps.setProperty("validationQueryTimeout", "2000")
    connProps
  }
} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:43,代码来源:MySQLFactory.scala

示例14: ConnectionProvider

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.commons.connections

import java.util.Properties
import javax.sql.DataSource

import com.aerospike.client.Host
import com.aerospike.client.async.{AsyncClient, AsyncClientPolicy}
import com.couchbase.client.java.{Cluster, CouchbaseCluster}
import org.apache.commons.dbcp2.BasicDataSourceFactory
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.hbase.client.{Connection, ConnectionFactory}

import scala.collection.JavaConverters._

class ConnectionProvider extends TConnectionProvider {

  override def createHbaseConnection(hConnConfig: Configuration): Connection = ConnectionFactory.createConnection(hConnConfig)

  override def createDatasourceConnection(mySQLProperties: Properties): DataSource = BasicDataSourceFactory.createDataSource(mySQLProperties)

  override def createCouchBaseConnection(nodes: List[String]): Cluster = CouchbaseCluster.create(nodes.asJava)

  override def createAeroSpikeConnection(nodes: List[String]): AsyncClient =  {
    val asyncClientPolicy = new AsyncClientPolicy()
    asyncClientPolicy.asyncMaxCommands = 500
    asyncClientPolicy.asyncSelectorThreads = 4
    new AsyncClient(asyncClientPolicy, nodes.map(new Host(_, 3000)): _ *)
  }
} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:30,代码来源:ConnectionProvider.scala

示例15: SystemConfiguration

//设置package包名称以及导入依赖的类
package com.github.mkorman9.districron

import javax.sql.DataSource

import akka.actor.ActorSystem
import com.typesafe.config.{Config, ConfigFactory}
import com.zaxxer.hikari.{HikariConfig, HikariDataSource}
import org.springframework.context.annotation.{Bean, ComponentScan, Configuration}
import org.springframework.scheduling.annotation.EnableScheduling

import scala.slick.driver.MySQLDriver.simple._

@Configuration
@ComponentScan
@EnableScheduling
class SystemConfiguration {
  final val ActorSystemName = "DistricronSystem"

  @Bean
  def config: Config = {
    ConfigFactory.load()
  }

  @Bean
  def actorSystem(config: Config): ActorSystem = {
    ActorSystem(ActorSystemName, config)
  }

  @Bean
  def dataSource(config: Config): DataSource = {
    val hikariConfig = new HikariConfig()
    hikariConfig.setDriverClassName(config.getString("datasource.jdbc-driver-class"))
    hikariConfig.setJdbcUrl(config.getString("datasource.jdbc-url"))
    hikariConfig.setUsername(config.getString("datasource.jdbc-username"))
    hikariConfig.setPassword(config.getString("datasource.jdbc-password"))
    hikariConfig.setMaxLifetime(config.getInt("datasource.poll-max-lifetime"))
    hikariConfig.setLeakDetectionThreshold(config.getInt("datasource.poll-leak-detection-threshold"))

    new HikariDataSource(hikariConfig)
  }

  @Bean
  def databaseConnection(dataSource: DataSource): Database = {
    Database.forDataSource(dataSource)
  }
} 
开发者ID:mkorman9,项目名称:districron,代码行数:47,代码来源:SystemConfiguration.scala


注:本文中的javax.sql.DataSource类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。