本文整理汇总了Scala中reactivemongo.api.MongoDriver类的典型用法代码示例。如果您正苦于以下问题:Scala MongoDriver类的具体用法?Scala MongoDriver怎么用?Scala MongoDriver使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MongoDriver类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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")
}
示例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()
}
}
示例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")
}
示例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")
}
}
示例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))
}
}
示例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
}
示例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)
})
})
}
}
}
示例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
}
示例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")
}
}
}
示例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()
}
}
示例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}.")
}
}
示例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))
}
示例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()
}
}
示例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] })
}