• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala MongoDriver类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: Customer

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

import reactivemongo.api.MongoDriver
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.BSONDocument
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

import scala.concurrent.Await

case class Customer(username:String,password:String,name:String,email:String,mobile:String)

case class Login(username:String,password:String)

class CustomerService {

  val driver = new MongoDriver
  val connection = driver.connection(List("localhost"))
  val database = Await.result(connection.database("sonu"),10.seconds)
  val collection= database.collection[BSONCollection]("customer")


  def insert(username:String,password:String,name:String,email:String,mobile:String):String ={
    try {
      val document = BSONDocument("username" -> username, "password" -> password, "name" -> name,
        "email" -> email, "mobile" -> mobile)
      Await.result(collection.insert(document), 10.seconds)
      "Inserted"
    }
    catch {
      case error:Exception => "Duplicate"
    }
  }

  def find(username:String,password:String):Boolean={
    try {
      val document = BSONDocument("username" -> username,"password" -> password)
      val result = Await.result(collection.find(document).one[BSONDocument], 10.seconds)
      if(result.isDefined) true else false
    }
    catch {
      case error:Exception => false
    }
  }
}

object CustomerService extends CustomerService 
开发者ID:sonumehrotra,项目名称:MongoAssignment,代码行数:48,代码来源:Customer.scala


示例2: db

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

import reactivemongo.api.{DefaultDB, MongoDriver}
import reactivemongo.core.nodeset.Authenticate
import scala.concurrent.ExecutionContext
//import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future //FIXME change for the actor execution context


trait DBConnection {
  val dbName = "cristal"
  val userName = "cristal"
  val password = "CristalRW2017"
  val driver = new MongoDriver
  val credentials = List(Authenticate(dbName, userName, password))
  val connection = driver.connection(List("localhost"), authentications = credentials)
  def db(implicit executor: ExecutionContext): Future[DefaultDB] = connection.database("cristal")
} 
开发者ID:frecano,项目名称:cristal,代码行数:19,代码来源:DBConnection.scala


示例3: ReactivemongoCollection

//设置package包名称以及导入依赖的类
package com.evojam.reactivemongo

import scala.concurrent.Future

import reactivemongo.api.MongoDriver
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson._
import scala.concurrent.ExecutionContext.Implicits.global

import com.evojam.Collection

class ReactivemongoCollection[Doc](
    driver: MongoDriver,
    collection: BSONCollection,
    implicit val reader: BSONDocumentReader[Doc],
    implicit val writer: BSONDocumentWriter[Doc]) extends Collection[Doc] {

  override val name = "reactivemongo"
  override def truncate(): Future[Unit] = collection.drop(failIfNotFound = false).map(_ => ())

  override def insert(doc: Doc): Future[Unit] = collection.insert(doc) map {
    case result if result.ok => ()
    case result => throw result.errmsg.map(new Exception(_)).getOrElse(new Exception("Unknown reactivemongo failure"))
  }

  override def get(id: String): Future[Option[Doc]] = collection.find(BSONDocument("_id" -> id)).one[Doc]

  override def close() = {
    collection.db.connection.close()
    driver.close()
  }
} 
开发者ID:evojam,项目名称:mongo-drivers-benchmarks,代码行数:33,代码来源:ReactivemongoCollection.scala


示例4: ReactivemongoProvider

//设置package包名称以及导入依赖的类
package com.evojam.reactivemongo

import scala.concurrent.ExecutionContext.Implicits.global

import reactivemongo.api.MongoDriver
import reactivemongo.bson.{BSONDocumentReader, BSONDocumentWriter}

import com.evojam.Collection

object ReactivemongoProvider {
  def apply[T](dbName: String, collectionName: String)(implicit reader: BSONDocumentReader[T], writer: BSONDocumentWriter[T]): Collection[T] = {
    val driver = new MongoDriver
    val connection = driver.connection(Seq("localhost"))
    val db = connection(dbName)
    val collection = db(collectionName)
    new ReactivemongoCollection[T](driver, collection, reader, writer)
  }
  def apply[T](implicit r: BSONDocumentReader[T], w: BSONDocumentWriter[T]): Collection[T] = apply[T]("test", "mongo-driver-benchmarks")

} 
开发者ID:evojam,项目名称:mongo-drivers-benchmarks,代码行数:21,代码来源:ReactivemongoProvider.scala


示例5: Main

//设置package包名称以及导入依赖的类
package com.aluxian.susucatbot

import com.aluxian.susucatbot.config.Config
import com.aluxian.susucatbot.controllers.{FacebookCtrl, RootCtrl}
import com.aluxian.susucatbot.utils.FutureBijection._
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.param.Stats
import com.twitter.finagle.{Http, Service}
import com.twitter.server.TwitterServer
import com.twitter.util.Await
import io.finch.Text
import io.finch.circe._
import reactivemongo.api.collections.bson._
import reactivemongo.api.{DefaultDB, MongoConnection, MongoDriver}

import scala.concurrent.ExecutionContext.Implicits.global

object Main extends TwitterServer {

  val endpoints = RootCtrl.root :+:
    FacebookCtrl.webhookVerify :+:
    FacebookCtrl.webhookNewEvent

  val api: Service[Request, Response] = endpoints.toServiceAs[Text.Plain]
  var db: DefaultDB = _

  def main() = {
    val server = Http.server
      .configured(Stats(statsReceiver))
      .serve(Config.listenAddress, api)

    onExit {
      server.close()
    }

    // MongoDB connection setup
    val driver = new MongoDriver()
    val parsedUri = MongoConnection.parseURI(Config.mongoUrl).get // TODO handle exception
    val connection = driver.connection(parsedUri)
    val databaseFuture = connection.database(parsedUri.db.get)
    println(">> awaiting db")
    db = Await.result(databaseFuture.asTwitter)
    println(">> got db")

    // Finagle admin panel
    Await.ready(adminHttpServer)
  }

  object collections {
    def users = db.collection("users")
    def messages = db.collection("messages")
  }

} 
开发者ID:aluxian,项目名称:SusuCatBot,代码行数:55,代码来源:Main.scala


示例6: Database

//设置package包名称以及导入依赖的类
package de.choffmeister.microserviceutils.mongodb

import akka.Done
import com.typesafe.config.ConfigFactory
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.{DefaultDB, MongoConnection, MongoDriver}

import scala.concurrent.{ExecutionContext, Future}

abstract class Database(val database: DefaultDB, collectionNamePrefix: String = "")(implicit ec: ExecutionContext) {
  def collection(name: String): BSONCollection = database.collection[BSONCollection](collectionNamePrefix + name)

  def init(): Future[Done]
  def clear(): Future[Done]
}

object Database {
  def open[DB <: Database](f: DefaultDB => DB)(implicit ec: ExecutionContext): Future[DB] = {
    val config = ConfigFactory.load().getConfig("mongodb")
    val uri = config.getString("uri")
    val databaseName = config.getString("database-name")

    val driver = MongoDriver()
    val mongodbUri = MongoConnection.parseURI(uri)
    val connection = Future.fromTry(mongodbUri.map(driver.connection))

    connection
      .flatMap(_.database(databaseName).map(f))
      .flatMap(db => db.init().map(_ => db))
  }
} 
开发者ID:choffmeister,项目名称:microservice-utils,代码行数:32,代码来源:Database.scala


示例7: authTimeout

//设置package包名称以及导入依赖的类
package com.rozilo.ussemble.services

import com.typesafe.config.ConfigFactory
import reactivemongo.api.{MongoConnectionOptions, DefaultDB, MongoConnection, MongoDriver}
import reactivemongo.core.nodeset.Authenticate
import scala.collection.JavaConverters._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.concurrent.duration.FiniteDuration

import scala.util.Try

trait DatabaseService {
  val config = ConfigFactory.load()
  val uri = config.getString("mongodb.uri")

  val servers = config.getString("mongodb.servers")
  val db_name = config.getString("mongodb.db_name")
  val user_name = config.getString("mongodb.db_user")
  val user_password = config.getString("mongodb.db_pass")

  implicit def authTimeout:FiniteDuration = {
    val timeoutDuration: Int = 5
    FiniteDuration(timeoutDuration, "seconds")
  }

  val conOpts = MongoConnectionOptions(sslEnabled = true, sslAllowsInvalidCert = true, keepAlive = true)

  val credentials7 = List(Authenticate(db_name, user_name, user_password))
  val connection4 = MongoService.driver.connection(servers.split(",").toList, options = conOpts)
  val mongoDB = connection4.database(db_name)
  mongoDB.flatMap { p =>
    p.authenticate(user_name, user_password) map {
      s =>
        println(s"MongoDB authentication success ${s}")
    } recover {
      case e: Exception =>
        e.printStackTrace()
        println(s"MongoDB authentication error: ${e.getMessage}")
    }
  }
}

object MongoService {
  val driver = new MongoDriver
} 
开发者ID:Rozilo,项目名称:uss-gallery,代码行数:47,代码来源:DatabaseService.scala


示例8: get

//设置package包名称以及导入依赖的类
package ru.svd.medan.infrastructure

import reactivemongo.api.{MongoConnection, MongoDriver}
import reactivemongo.api.collections.bson.BSONCollection
import scala.concurrent.ExecutionContext.Implicits.global

import scala.concurrent.Future



trait MongoDBCollectionProvider {
  def get(collectionName: String): Future[(BSONCollection, MongoConnection)]
}

object MongoDBCollectionProvider {
  private val driver = new MongoDriver()

  def fromUriAndDatabase(uri: String, database: String): MongoDBCollectionProvider = {
    (collectionName: String) => {
      Future.fromTry(MongoConnection.parseURI(uri))
        .map((uri) => driver.connection(uri))
        .flatMap((con) => {
          con.database(database).map((db) => {
            (db.collection(collectionName), con)
          })
        })
    }
  }
} 
开发者ID:severiand,项目名称:medan,代码行数:30,代码来源:MongoDBCollectionProvider.scala


示例9: MongoRepository

//设置package包名称以及导入依赖的类
package io.shedin.crud.mongo

import io.shedin.crud.lib.CrudRepository
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.{DefaultDB, MongoConnection, MongoConnectionOptions, MongoDriver}
import reactivemongo.bson.{BSONDocumentReader, BSONDocumentWriter, document}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

// TODO maybe should just mix in AsyncCrudOperations[T] instead of CrudRepository[T]
abstract class MongoRepository[T]
(databaseName: String)
(implicit writer: BSONDocumentWriter[T], reader: BSONDocumentReader[T], manifest: Manifest[T])
  extends CrudRepository[T] {

  private lazy val mongoUri = s"mongodb://localhost:27017/$databaseName?authMode=scram-sha1"
  private lazy val eventualMongoConnection = Future.fromTry(MongoConnection.parseURI(mongoUri).map(MongoDriver().connection(_)))

  private def mongoDatabase: Future[DefaultDB] = eventualMongoConnection.flatMap(_.database(databaseName))

  private def mongoCollection = mongoDatabase.map(_.collection[BSONCollection](simpleName(manifest)))

  override def create(resource: T): Future[T] =
    mongoCollection.flatMap { bsonCollection =>
      bsonCollection.insert(resource).map { writeResult =>
        if (writeResult.n == 1) resource
        else throw new RuntimeException(s"failed to persist resource [$resource]")
      }
    }

  override def read(resourceId: String): Future[Option[T]] = {
    mongoCollection.flatMap(_.find(document("id" -> resourceId)).cursor[T]().collect[List]()) map (_.headOption)
  }

  override def update(resourceId: String, resource: T): Future[Option[T]] = {
    mongoCollection.flatMap(_.update(document("id" -> resourceId), resource)) map { updateWriteResult =>
      if (updateWriteResult.n == 0) None
      else if (updateWriteResult.n == 1) Some(resource)
      else throw new RuntimeException("more than one doc updated") // TODO revisit this
    }
  }

  override def update(resourceId: String, updatePayload: String): Future[Option[AnyRef]] = throw new UnsupportedOperationException

  override def delete(resourceId: String): Future[Boolean] =
    mongoCollection.flatMap(_.remove(document("id" -> resourceId))) map (_.n > 0)

  private def simpleName[T](manifest: Manifest[T]): String =
    manifest.runtimeClass.getSimpleName.toLowerCase

} 
开发者ID:edinhodzic,项目名称:shedin-crud-mongo,代码行数:53,代码来源:MongoRepository.scala


示例10: MongoUtils

//设置package包名称以及导入依赖的类
package com.ringcentral.gatling.mongo

import reactivemongo.api.MongoConnection.{ParsedURI, URIParsingException}
import reactivemongo.api.{DefaultDB, MongoConnection, MongoDriver}

import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{Await, Future}
import scala.util.{Failure, Success, Try}

// fixme remove global context
import scala.concurrent.ExecutionContext.Implicits.global

object MongoUtils {

  private val defaultPort: Int = 27017
  private lazy val mongoDriver = new MongoDriver()

  private def establishConnection(uri: ParsedURI, dbName: String, connectionTimeout: FiniteDuration): DefaultDB = {
    Await.result(establishConnection(uri, dbName), connectionTimeout)
  }

  private def establishConnection(uri: ParsedURI, dbName: String): Future[DefaultDB] =
    Try(mongoDriver.connection(uri).database(dbName))
    match {
      case Success(db) => db
      case Failure(err) =>
        throw new IllegalStateException(s"Can't connect to database ${printHosts(uri.hosts)}: ${err.getMessage}", err)
    }

  private def printHosts(hosts: List[(String, Int)]): String = hosts.map { case (host, port) => s"$host:$port" }.mkString(", ")

  def connectToDB(uri: ParsedURI, connectionTimeout: FiniteDuration): DefaultDB =
    uri.db match {
      case Some(dbName) => establishConnection(uri, dbName, connectionTimeout)
      case None => throw new IllegalStateException(s"Can't connect to database $uri.")
    }

  def connectToDB(uri: String, connectionTimeout: FiniteDuration): DefaultDB =  connectToDB(parseUri(uri), connectionTimeout)

  def parseHosts(hosts: Seq[String]): Seq[(String, Int)] = hosts.map { hostAndPort =>
    hostAndPort.split(':').toList match {
      case host :: port :: Nil =>
        host -> Try(port.toInt).filter(p => p > 0 && p < 65536)
          .getOrElse(throw new URIParsingException(s"Could not parse hosts '$hosts' from URI: invalid port '$port'"))
      case host :: Nil =>
        host -> defaultPort
      case _ => throw new URIParsingException(s"Could not parse hosts from URI: invalid definition '$hosts'")
    }
  }

  def parseUri(uri: String): ParsedURI = {
    MongoConnection.parseURI(uri) match {
      case Success(parsedUri) => parsedUri
      case Failure(err) => throw new IllegalStateException(s"Can't parse database uri. $err")
    }
  }
} 
开发者ID:RC-Platform-Disco-Team,项目名称:gatling-mongodb-protocol,代码行数:58,代码来源:MongoUtils.scala


示例11: SpecificationConstants

//设置package包名称以及导入依赖的类
package com.clemble.query

import com.sksamuel.elastic4s.ElasticDsl._
import com.sksamuel.elastic4s.mappings.FieldType.{IntegerType, StringType}
import com.sksamuel.elastic4s.{ElasticsearchClientUri, ElasticClient}
import reactivemongo.api.MongoDriver

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

case object SpecificationConstants {

  val db = Await.result(MongoDriver().connection(List("localhost:27017")).database("test"), 1 minute)

  val client: ElasticClient = {
    val uri = ElasticsearchClientUri("localhost", 9300)
    val client = ElasticClient.transport(uri)
    initClient(client)
    client
  }

  private def initClient(client: ElasticClient) = {
    val needToRemove = client.execute(indexExists("test")).map(_.isExists()).await
    if (needToRemove) {
      require(client.execute(deleteIndex("test")).await().isAcknowledged())
    }

    val nameMapping = mapping("employee").fields(
      field("name", StringType).index("not_analyzed"),
      field("salary", IntegerType)
    )
    val createCommand = create index "test" mappings (nameMapping)

    val createResponse = client.execute(createCommand).await
    createResponse.isAcknowledged()
  }

} 
开发者ID:clemble,项目名称:scala-query-dsl,代码行数:40,代码来源:SpecificationConstants.scala


示例12: MongoTweetCollectionProvider

//设置package包名称以及导入依赖的类
package io.github.bszwej.core.mongo

import com.typesafe.scalalogging.LazyLogging
import io.github.bszwej.MainConfig
import reactivemongo.api.MongoDriver
import reactivemongo.api.collections.bson.BSONCollection

import scala.concurrent.Future
import scala.util.{Failure, Success}

object MongoTweetCollectionProvider extends MainConfig with LazyLogging {

  import scala.concurrent.ExecutionContext.Implicits.global

  private val driver: MongoDriver = MongoDriver()
  private val connection = Future.fromTry(driver.connection("mongodb://localhost:27017"))

  private val database = connection.flatMap(_.database(config.getString("mongo.database-name")))
  val collection: Future[BSONCollection] = database.map(_.collection[BSONCollection](config.getString("mongo.collection-name")))

  database.onComplete {
    case Success(db) ?
      logger.info(s"Successfully connected to the database '${db.name}'.")

    case Failure(e) ?
      logger.error(s"Error connection to the database: ${e.getMessage}.")
  }
} 
开发者ID:bszwej,项目名称:akka-microservice,代码行数:29,代码来源:MongoTweetCollectionProvider.scala


示例13:

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

import java.util.concurrent.Executors

import com.typesafe.config.ConfigFactory
import reactivemongo.api.{DefaultDB, MongoConnectionOptions, MongoDriver, ScramSha1Authentication}

import scala.collection.JavaConverters._
import scala.concurrent.{ExecutionContext, Future}

trait MongoConnection {
  implicit val ec = ExecutionContext.fromExecutor(Executors.newCachedThreadPool())

  private val config   = ConfigFactory.load()
  private val database = config.getString("mongodb.db")
  private val servers  = config.getStringList("mongodb.servers").asScala

  private val driver = new MongoDriver
  private lazy val connection = driver.connection(
    nodes = servers,
    options = MongoConnectionOptions(authMode = ScramSha1Authentication)
  )

  lazy val dbFuture: Future[DefaultDB] = connection
    .authenticate(
      db = database,
      user = config.getString("mongodb.user"),
      password = config.getString("mongodb.password")
    )
    .flatMap(authentication => connection.database(database))
} 
开发者ID:Leonti,项目名称:receipts-rest-service,代码行数:32,代码来源:MongoConnection.scala


示例14: Blog

//设置package包名称以及导入依赖的类
package me.lsbengine.server

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import com.github.nscala_time.time.Imports._
import com.typesafe.config.ConfigFactory
import reactivemongo.api.{MongoConnection, MongoDriver}
import sun.misc.Signal

import scala.concurrent.ExecutionContext

object Blog extends App {
  val conf = ConfigFactory.load()
  implicit val system = ActorSystem("server", conf)
  implicit val context = ExecutionContext.Implicits.global
  implicit val materializer = ActorMaterializer()(system)

  val driver = new MongoDriver
  val mongoHost = BlogConfiguration.mongoDBHost
  val mongodbName = BlogConfiguration.mongoDBName
  val connection: MongoConnection = driver.connection(List(mongoHost))
  val hostName = BlogConfiguration.hostName
  val publicPort = BlogConfiguration.publicPort
  val adminPort = BlogConfiguration.adminPort

  val publicService = new PublicService(connection, mongodbName, Http().system.log)
  val adminService = new AdminService(connection, mongodbName, Http().system.log)

  DateTimeZone.setDefault(DateTimeZone.forID("UTC"))

  Http().bindAndHandle(publicService.routes, hostName, publicPort)
  Http().bindAndHandle(adminService.routes, hostName, adminPort)

  Signal.handle(new Signal("INT"), (_: Signal) => {
    shutdown()
  })

  Signal.handle(new Signal("TERM"), (_: Signal) => {
    shutdown()
  })

  private def shutdown(): Unit = {
    println("System is shutting down...")
    Http().shutdownAllConnectionPools()
    Http().system.terminate()
    connection.close()
    driver.system.terminate()
    driver.close()
    system.terminate()
  }
} 
开发者ID:jrabasco,项目名称:LSBEngine,代码行数:53,代码来源:Blog.scala


示例15: MongoUserRepository

//设置package包名称以及导入依赖的类
package com.example.graphql.service

import reactivemongo.core.commands.FindAndModify

import reactivemongo.bson.BSONDocumentReader

import reactivemongo.bson.Macros

import reactivemongo.api.MongoConnection
import reactivemongo.api.MongoDriver
import com.example.graphql.model.User
import reactivemongo.bson.BSONDocumentWriter
import com.example.graphql.model.Address
import com.example.graphql.model.Company
import scala.concurrent.Future
import reactivemongo.api.DefaultDB
import java.time.LocalDateTime
import java.util.Locale
import com.example.graphql.model.Role
import reactivemongo.api.commands._  

class MongoUserRepository extends Repository {
  import scala.concurrent.ExecutionContext.Implicits.global
  import reactivemongo.bson._
  
  val mongoUri = "mongodb://192.168.99.100:27017/mydb?authMode=scram-sha1"
  val connection = MongoConnection.parseURI(mongoUri).map(MongoDriver().connection(_))
  val futureConnection = Future.fromTry(connection)
  
  def db: Future[DefaultDB] = futureConnection.flatMap(_.database("mydb"))
  def collection = db.map(_.collection("users"))
  
  implicit def addressWriter: BSONDocumentWriter[Address] = Macros.writer[Address]
  implicit def addressReader: BSONDocumentReader[Address] = Macros.reader[Address]
  implicit def companyWriter: BSONDocumentWriter[Company] = Macros.writer[Company]
  implicit def companyReader: BSONDocumentReader[Company] = Macros.reader[Company]
  implicit def userWriter: BSONDocumentWriter[User] = Macros.writer[User]
  implicit def userReader: BSONDocumentReader[User] = Macros.reader[User]
  
  def findAll(fields: Seq[String]): Future[Seq[User]] = collection.flatMap(
      _.find(document())
        //.projection(fields.foldLeft(document())((doc, field) => doc.add(field -> BSONInteger(1))))
        .cursor[User]()
        .collect[Seq]()
    )
      
   def findById(id: Long): Future[Option[User]] = collection.flatMap(
      _.find(document("id" -> BSONLong(id))).one[User]
    )
    
  def addUser(email: String, firstName: Option[String], lastName: Option[String], roles: Seq[Role.Value]): Future[User] = {
    val user = User(BSONObjectID.generate().time, email, LocalDateTime.now(), firstName, lastName, roles, false, false, Locale.CANADA, Company(1, "Tommyknockers, Inc.", Address()), Address())
    collection.flatMap(_.insert(user).map(_ => user))
  }
  
   def activateById(id: Long): Future[Option[User]] =
    collection.flatMap(_.findAndUpdate(document("id" -> BSONLong(id)), 
      document("$set" -> document("activated" -> BSONBoolean(true))), fetchNewObject = true).map { _.result[User] })
} 
开发者ID:aredko-appdirect,项目名称:akka-http-graphql,代码行数:60,代码来源:MongoUserRepository.scala


示例16: map

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

import de.flapdoodle.embed.mongo.MongodStarter
import de.flapdoodle.embed.mongo.config.{MongodConfigBuilder, Net}
import de.flapdoodle.embed.mongo.distribution.Version
import de.flapdoodle.embed.process.runtime.Network
import org.specs2.mutable.Specification
import org.specs2.specification.core.Fragments
import reactivemongo.api.{MongoConnection, MongoDriver}

trait EmbeddedConnection extends Specification {
  val Port = 12345
  private val starter = MongodStarter.getDefaultInstance
  private val mongodConfig = new MongodConfigBuilder()
    .version(Version.Main.PRODUCTION)
    .net(new Net(Port, Network.localhostIsIPv6()))
    .build()
  private val mongodExecutable = starter.prepare(mongodConfig)

  override def map(fs: => Fragments) = startMongo ^ fs ^ stopMongo

  private def startMongo = step {
    mongodExecutable.start
    Thread.sleep(2000)
    success
  }

  private def stopMongo() = step {
    Thread.sleep(10000)
    mongodExecutable.stop()
    success
  }

  def getConnection: MongoConnection = {
    Thread.sleep(2000)
    val driver = new MongoDriver
    val connection = driver.connection("localhost:12345" :: Nil)
    Thread.sleep(2000)
    connection
  }
} 
开发者ID:salceson,项目名称:toik-games-price-comparator,代码行数:42,代码来源:EmbeddedConnection.scala


示例17: MongoService

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

import javax.inject.Inject
import javax.inject.Singleton

import play.api.Configuration

import reactivemongo.api.MongoConnection
import reactivemongo.api.MongoDriver
import reactivemongo.api.collections.bson.BSONCollection

import scala.concurrent.ExecutionContext.Implicits.global

@Singleton
class MongoService @Inject()(config: Configuration) {
  // if no host names found, default to localhost:27017
  lazy val hostURI = config.getString("mongodb.server")
                           .getOrElse("localhost:27017")
                           .toString()

  // if no db name found, default to test
  lazy val dbName = config.getString("mongodb.db").getOrElse("test")

  lazy val driver = new MongoDriver
  lazy val connection = driver.connection(List(hostURI))
  lazy val database = connection.database(dbName)

  lazy val beacons = database.map(_.collection("beacons"))
  lazy val users = database.map(_.collection("users"))
} 
开发者ID:tninesling,项目名称:BeaconServer,代码行数:31,代码来源:MongoService.scala



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala _类代码示例发布时间:2022-05-23
下一篇:
Scala GenMap类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap