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 ...
随机推荐
- torch.nn.LSTM()函数维度详解
123456789101112lstm=nn.LSTM(input_size, hidden_size, num_la ...
- 2019-10-5-dotnet-core-获取-MacAddress-地址方法
title author date CreateTime categories dotnet core 获取 MacAddress 地址方法 lindexi 2019-10-05 10:44:10 + ...
- Flex AIR自定义Mobile的弹出框组件
做Flex Mobile开发的人应该知道,Flex为手机应用并没有提供弹出框组件,需要自定义. 通过查找文档.资料,我做出一个效果还算不错的弹出框组件,可以适用于手机设备上,不多讲,直接贴源码,相信对 ...
- Codeforces Round #564 (Div. 2)
传送门 参考资料 [1]: the Chinese Editoria A. Nauuo and Votes •题意 x个人投赞同票,y人投反对票,z人不确定: 这 z 个人由你来决定是投赞同票还是反对 ...
- gitLab操作规范和项目流程
刚做完一个项目并且艰难得上线,对整个项目流程和gitLab规范 有了一些心得,给新来的同学普及一下. 最先产品会写一篇需求文档,咱们要先看需求文档对项目有一个大致了解,然后产品喊后端.ui.前端 一 ...
- MobaXterm 使用中间服务器
经常需要连接服务器,但是有时候服务器需要经过一层中间服务器才可以连接,所以本文告诉大家如何使用MobaXterm 配置中间服务器,进行ssh连接 在本文的开始,本地转发服务器已经弄好,本文不会告诉大家 ...
- WCF 服务应用程序
1. 创建 WCF 服务程序和客户端程序,参考如下: https://docs.microsoft.com/zh-cn/dotnet/framework/wcf/getting-started-tut ...
- 关于启动php-fpm失败的解决办法
当我执行 sudo lnmp php-fpm restart会出现如下错误 Starting php-fpm /usr/local/php/sbin/php-fpm: error while load ...
- char* 、const char*和string之间的转换
1. const char* 和string 转换 (1) const char*转换为 string,直接赋值即可. EX: const char* tmp = "tsinghua ...
- 第三阶段:3.Web端产品设计:4.产品设计-交互设计
交互设计主要做框架层以及结构层.包括交互关系,信息结构,界面布局,导航设计,信息内容. 导航关系非常重要. 这是框架层. 这是结构层. 要素就是信息内容.