Scala与Mongodb实践2-----图片、日期的存储读取
目的:在IDEA中实现图片、日期等相关的类型在mongodb存储读取
- 主要是Scala和mongodb里面的类型的转换。Scala里面的数据编码类型和mongodb里面的存储的数据类型各个不同。存在类型转换。
- 而图片和日期的转换如下图所示。

1、日期的存取
- 简单借助java.until.Calendar即可。
val ca=Calendar.getInstance()
ca.set()
ca.getTime
- 有多种具体的格式等,再直接应用mgoDateTime等方法
//显示各种格式
type MGODate = java.util.Date
def mgoDate(yyyy: Int, mm: Int, dd: Int): MGODate = {
val ca = Calendar.getInstance()
ca.set(yyyy,mm,dd)
ca.getTime()
}
def mgoDateTime(yyyy: Int, mm: Int, dd: Int, hr: Int, min: Int, sec: Int): MGODate = {
val ca = Calendar.getInstance()
ca.set(yyyy,mm,dd,hr,min,sec)
ca.getTime()
}
def mgoDateTimeNow: MGODate = {
val ca = Calendar.getInstance()
ca.getTime
}
def mgoDateToString(dt: MGODate, formatString: String): String = {
val fmt= new SimpleDateFormat(formatString)
fmt.format(dt)
}
2、图片的存取(看图片大小,一般都是如下,大于16M的图片即采用GridFS,分别将图片的属性存储)
借助Akka的FileStream
将File(图片)===》Array[Byte]代码格式,图片在mongodb中显示形式binary
具体代码如下:
FileStreaming.scala
package com.company.files import java.nio.file.Paths
import java.nio._
import java.io._
import akka.stream.{Materializer}
import akka.stream.scaladsl.{FileIO, StreamConverters} import scala.concurrent.{Await}
import akka.util._
import scala.concurrent.duration._ object FileStreaming {
def FileToByteBuffer(fileName: String, timeOut: FiniteDuration)(
implicit mat: Materializer):ByteBuffer = {
val fut = FileIO.fromPath(Paths.get(fileName)).runFold(ByteString()) { case (hd, bs) =>
hd ++ bs
}
(Await.result(fut, timeOut)).toByteBuffer
} def FileToByteArray(fileName: String, timeOut: FiniteDuration)(
implicit mat: Materializer): Array[Byte] = {
val fut = FileIO.fromPath(Paths.get(fileName)).runFold(ByteString()) { case (hd, bs) =>
hd ++ bs
}
(Await.result(fut, timeOut)).toArray
} def FileToInputStream(fileName: String, timeOut: FiniteDuration)(
implicit mat: Materializer): InputStream = {
val fut = FileIO.fromPath(Paths.get(fileName)).runFold(ByteString()) { case (hd, bs) =>
hd ++ bs
}
val buf = (Await.result(fut, timeOut)).toArray
new ByteArrayInputStream(buf)
} def ByteBufferToFile(byteBuf: ByteBuffer, fileName: String)(
implicit mat: Materializer) = {
val ba = new Array[Byte](byteBuf.remaining())
byteBuf.get(ba,0,ba.length)
val baInput = new ByteArrayInputStream(ba)
val source = StreamConverters.fromInputStream(() => baInput) //ByteBufferInputStream(bytes))
source.runWith(FileIO.toPath(Paths.get(fileName)))
} def ByteArrayToFile(bytes: Array[Byte], fileName: String)(
implicit mat: Materializer) = {
val bb = ByteBuffer.wrap(bytes)
val baInput = new ByteArrayInputStream(bytes)
val source = StreamConverters.fromInputStream(() => baInput) //ByteBufferInputStream(bytes))
source.runWith(FileIO.toPath(Paths.get(fileName)))
} def InputStreamToFile(is: InputStream, fileName: String)(
implicit mat: Materializer) = {
val source = StreamConverters.fromInputStream(() => is)
source.runWith(FileIO.toPath(Paths.get(fileName)))
}
}
- Helpers.scala
package com.company.lib import java.util.concurrent.TimeUnit import scala.concurrent.Await
import scala.concurrent.duration.Duration
import java.text.SimpleDateFormat
import java.util.Calendar
import org.mongodb.scala._ object Helpers { implicit class DocumentObservable[C](val observable: Observable[Document]) extends ImplicitObservable[Document] {
override val converter: (Document) => String = (doc) => doc.toJson
} implicit class GenericObservable[C](val observable: Observable[C]) extends ImplicitObservable[C] {
override val converter: (C) => String = (doc) => doc.toString
} trait ImplicitObservable[C] {
val observable: Observable[C]
val converter: (C) => String def results(): Seq[C] = Await.result(observable.toFuture(), Duration(10, TimeUnit.SECONDS))
def headResult() = Await.result(observable.head(), Duration(10, TimeUnit.SECONDS))
def printResults(initial: String = ""): Unit = {
if (initial.length > 0) print(initial)
results().foreach(res => println(converter(res)))
}
def printHeadResult(initial: String = ""): Unit = println(s"${initial}${converter(headResult())}")
} type MGODate = java.util.Date
def mgoDate(yyyy: Int, mm: Int, dd: Int): MGODate = {
val ca = Calendar.getInstance()
ca.set(yyyy,mm,dd)
ca.getTime()
}
def mgoDateTime(yyyy: Int, mm: Int, dd: Int, hr: Int, min: Int, sec: Int): MGODate = {
val ca = Calendar.getInstance()
ca.set(yyyy,mm,dd,hr,min,sec)
ca.getTime()
}
def mgoDateTimeNow: MGODate = {
val ca = Calendar.getInstance()
ca.getTime
} def mgoDateToString(dt: MGODate, formatString: String): String = {
val fmt= new SimpleDateFormat(formatString)
fmt.format(dt)
} }
- Model.scala
模型中包含了两个具体的模型Person和Address,二者是包含关系,具体模型内含存取方法

package com.company.demo import org.mongodb.scala._
import bson._
import java.util.Calendar
import com.company.files._ import akka.stream.ActorMaterializer object Models {
//Model可存在在不同的模型,下面存在一个拥有代表性的模型Person case class Address(
//Scala中的字段类型,且String的默认参数是“”
city: String ="",
zipcode: String = ""
) {
def toDocument: Document =
bson.Document(
//bson.Document是bson包里面的Document,其他包内有不同的Document
"city" -> city,
"zipcode" -> zipcode
)
def fromDocument(doc: Document): Address =
this.copy(
city = doc.getString("city"),
zipcode = doc.getString("zipcode")
)
}
//这是日期的设置
val ca = Calendar.getInstance()
ca.set(2001,10,23)
val defaultDate = ca.getTime
case class Person (
lastName: String = "Doe",
firstName: String = "John",
age: Int = 1,
phones: List[String] = Nil,
address: List[Address] = Nil,
birthDate: java.util.Date = defaultDate,
picture: Array[Byte] = Array()
) { ctx =>
def toDocument: Document = {
var doc = bson.Document(
"lastName" -> ctx.lastName,
"firstName" -> ctx.firstName,
"age" -> ctx.age,
"birthDate" -> ctx.birthDate
)
if (ctx.phones != Nil)
doc = doc + ("phones" -> ctx.phones)
if (ctx.address != Nil)
doc = doc + ("address" -> ctx.address.map(addr => addr.toDocument))
if (!ctx.picture.isEmpty)
doc = doc + ("picture" -> ctx.picture) doc }
import scala.collection.JavaConverters._
def fromDocument(doc: Document): Person = {
//keySet
val ks = doc.keySet
ctx.copy(
lastName = doc.getString("lastName"),
firstName = doc.getString("firstName"),
age = doc.getInteger("age"),
phones = {
doc.get("phones").asInstanceOf[Option[BsonArray]] match {
case Some(barr) => barr.getValues.asScala.toList.map(_.toString)
case None => Nil
}
},
address = {
if (ks.contains("address")) {
doc.get("address").asInstanceOf[Option[BsonArray]] match {
case Some(barr) => barr.getValues.asScala.toList.map (
ad => Address().fromDocument(ad.asDocument())
)
case None => Nil
}
}
else Nil
},
picture = {
if (ks.contains("picture")) {
doc.get("picture").asInstanceOf[Option[BsonBinary]] match {
case Some(ba) => ba.getData
case None => Array()
}
}
else Array()
}
)
}
//在控制台显示的格式。
def toSink()(implicit mat: ActorMaterializer) = {
println(s"LastName: ${ctx.lastName}")
println(s"firstName: ${ctx.firstName}")
println(s"age: ${ctx.age}")
println(s"phones: ${ctx.phones}")
println(s"address ${ctx.address}")
if(!ctx.picture.isEmpty) {
val path = s"/img/${ctx.firstName}.jpg"
FileStreaming.ByteArrayToFile(ctx.picture,path)
println(s"picture saved to: ${path}")
}
} } }
- PersonCRUD.scala简单测试
package com.company.demo import org.mongodb.scala._
import bson._
import java.util.Calendar
import scala.collection.JavaConverters._
import com.company.lib.Helpers._
import com.company.files.FileStreaming._
import akka.actor._
import akka.stream._
import scala.concurrent.duration._
import scala.util._ object PersonCRUD extends App {
import Models._ implicit val system = ActorSystem()
implicit val ec = system.dispatcher
implicit val mat = ActorMaterializer() // or provide custom MongoClientSettings
val settings: MongoClientSettings = MongoClientSettings.builder()
.applyToClusterSettings(b => b.hosts(List(new ServerAddress("localhost")).asJava))
.build()
val client: MongoClient = MongoClient(settings)
val mydb = client.getDatabase("mydb")
val mytable = mydb.getCollection("personal") val susan = Person(
lastName = "Wang",
firstName = "Susan",
age = 18,
phones = List("137110998","189343661"),
address = List(
Address("Sz","101992"),
Address(city = "gz", zipcode="231445")
),
birthDate = mgoDate(2001,5,8),
picture = FileToByteArray("/img/sc.jpg",3 seconds)
)
/*
val futResult = mytable.insertOne(susan.toDocument).toFuture() futResult.onComplete {
case Success(value) => println(s"OK! ${value}")
case Failure(err) => println(s"Boom!!! ${err.getMessage}")
} scala.io.StdIn.readLine() */
mytable.find().toFuture().andThen {
case Success(ps) => ps.foreach(Person().fromDocument(_).toSink())
case Failure(err) => println(s"ERROR: ${err.getMessage}")
}
scala.io.StdIn.readLine()
system.terminate()
}
Scala与Mongodb实践2-----图片、日期的存储读取的更多相关文章
- Scala与Mongodb实践4-----数据库操具体应用
目的:在实践3中搭建了运算环境,这里学会如何使用该环境进行具体的运算和相关的排序组合等. 由数据库mongodb操作如find,aggregate等可知它们的返回类型是FindObservable.A ...
- Scala与Mongodb实践3-----运算环境的搭建
目的:使的在IDEA中编辑代码,令代码实现mongodb运算,且转换较为便捷 由实验2可知,运算环境的搭建亦需要对数据进行存储和计算,故需要实现类型转换,所以在实验2的基础上搭建环境. 由菜鸟教程可得 ...
- Scala与Mongodb实践1-----mongodbCRUD
目的:如何使用MongoDB之前提供有关Scala驱动程序及其异步API. 1.现有条件 IDEA中的:Scala+sbt+SDK mongodb-scala-driver的网址:http://mon ...
- Python中使用Flask、MongoDB搭建简易图片服务器
主要介绍了Python中使用Flask.MongoDB搭建简易图片服务器,本文是一个详细完整的教程,需要的朋友可以参考下 1.前期准备 通过 pip 或 easy_install 安装了 pymong ...
- 使用Scala操作Mongodb
介绍 Scala是一种功能性面向对象语言.它融汇了很多前所未有的特性.而同一时候又执行于JVM之上.随着开发人员对Scala的兴趣日增,以及越来越多的工具支持,无疑Scala语言将成为你手上一件不可缺 ...
- Scala对MongoDB的增删改查操作
=========================================== 原文链接: Scala对MongoDB的增删改查操作 转载请注明出处! ==================== ...
- 【Scala】Scala多线程-并发实践
Scala多线程-并发实践 scala extends Thread_百度搜索 scala多线程 - 且穷且独立 - 博客园 Scala和并发编程 - Andy Tech Talk - ITeye博客 ...
- 一个从MongoDB中导出给定日期范围内数据的shell脚本
#!/bin/sh ver=`date "+%Y%m%d"` #d1, the beginning date, eg:2017-06-28 d1=$1 d1=`date -d $d ...
- Scala操作MongoDB
Scala操作MongoDB // Maven <dependencies> <dependency> <groupId>org.mongodb</group ...
随机推荐
- 2016.1.22 扩充临时表空间解决ora-01652错误
今天运行一个复杂查询时报错ora-01652 无法通过128 扩展temp段, 网上说是临时表空间大小不够,运行了脚本调整临时表空间,问题解决 alter database tempfile '/ap ...
- java方法特点
它可以实现独立的功能; 必须定义在类里面; 它只有被调用才会执行; 它可以被重复使用; 方法结束后方法里的对象失去引用; 如何定义一个功能,并通过方法体现出来: ① 明确该功能运算后的结果.明确返回值 ...
- Redux 初始化完整结构
文件管理 目录文档 ★★★index.js★★★ ★★★app.js★★★ ★★★store->index.js★★★ ★★★actions->index.js★★★ ★★★store-& ...
- golang http get请求方式
client := &http.Client{} //生成要访问的url,token是api鉴权,每个api访问方式不同,根据api调用文档拼接URLurl := fmt.Sprintf(&q ...
- H3C 单路径网络中环路产生过程(3)
- vue-learning:33 - component - 内置组件 - 过渡组件transition
vue内置过渡组件transition 目录 什么是过渡 基本过渡或动画实现的语法 css过渡动画:transition / animation js过渡:特定事件钩子函数 各种情形下的过渡实现,使用 ...
- 轮播图模块(vue)
轮播图模块(vue) 通过属性方式传值 值为一个数组.每一项含有imgUrl(图片地址).link(跳转链接),link为可选属性 <template> <div class=&qu ...
- (转载)window安装mysql
一.MYSQL的安装 1.打开下载的mysql安装文件mysql-5.5.27-win32.zip,双击解压缩,运行“setup.exe”. 2.选择安装类型,有“Typical(默认)”.“Comp ...
- .NET进阶篇07-.NET和COM
知识需要不断积累.总结和沉淀,思考和写作是成长的催化剂 内容目录 一.COM和.NET元数据内存管理接口注册线程编组二..NET客户端调用COM组件三.COM客户端调用.NET组件四.嵌入互操作类型五 ...
- world 文档中表格旋转180°
一个好朋友给我打电话,说是有个wps操作把他难住了,他常年跟wps 形影不离,你都搞不定,我都不怎么用.听完他说的以后,我才明白他要的效果是怎么样的,贴图来看: 其实像直接转化成这种效果没有办法,但是 ...