- 浏览: 2539972 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
Spray(5)REST API Project - Recall and Prepare Project
1. Recall some ideas
These things consist of all the modules we are using.
spray-can, spray-routing, spray-io, spray-http, spray-util, spray-testkit, spray-json
How we deal with HTTP
def receive = {
case HttpRequest(HttpMethods.GET, "/", _, _, _) =>
sender ! index
case HttpRequest(HttpMethods.GET, "/stop", _, _, _) =>
sender ! HttpResponse(entity = "Shutting down in 1 second ...")
context.system.scheduler.scheduleOnce(1 second span, new Runnable { def run() { context.system.shutdown() } })
case HttpRequest(GET, "/server-stats", _, _, _) =>
valclient = sender
(context.actorFor("../http-server") ? HttpServer.GetStats).onSuccess {
casex: HttpServer.Stats => client ! statsPresentation(x)
}
case HttpRequest(GET, "/io-stats", _, _, _) =>
valclient = sender
(IOExtension(context.system).ioBridge() ? IOBridge.GetStats).onSuccess {
case IOBridge.StatsMap(map) => client ! statsPresentation(map)
}
case HttpRequest(HttpMethods.GET, "/event", _, _, _) =>
sender ! ok
}
Spray Routing
class MyService extends Actor with HttpServiceActor {
def receive = handleTimeouts orElse runRoute(myRoute)
def myRoute: Route = `<my-route-definition>`
def handleTimeouts: Receive = {
case Timeout(x: HttpRequest) =>
sender ! HttpResponse(StatusCodes.InternalServerError, "Too late")
} }
The ~ operator was introduced, which connects two routes in a way that allows a second route to get a go at a request if the first route "rejected" it.
Spray-json
Then I can parse the string to AST abstract Syntax Tree(AST).
1.1. String to AST
valjson1 = """{ "streetNumber": "A1", "street" : "Main Street", "city" : "Colombo" }"""
valjson2 = """{ "name" : "John", "age" : 26, "sex" : 0 , "address" : { "streetNumber": "A1", "street" : "Main Street", "city" : "Colombo" }}"""
//string to AST
valaddressAST = json1.asJson //or JsonParser(source)
valpersonAST = json2.asJson
1.2. AST to String
//AST to string
println(addressAST.compactPrint) //or .compactPrint
println(personAST.prettyPrint)
1.3. AST to Object
import AddressJsonProtocol._
//AST 2 Object
val address1 = addressAST.convertTo[Address]
1.4. Object to AST
//Object 2 AST
valaddressAST2 = address1.toJson
Slick
Do with slick and native SQL.
2. Prepare a New Project
I need to add something to build.sbt to make some sbt commands works.
sbt>re-start
sbt>re-stop
sbt>assembly
build.sbt
import AssemblyKeys._
seq(Revolver.settings: _*)
mainClass in assembly := Some("com.sillycat.easysprayrestserver.Boot")
artifact in (Compile, assembly) ~= { art =>
art.copy(`classifier` = Some("assembly"))
}
excludedJars in assembly <<= (fullClasspath in assembly) map { cp =>
cp filter {_.data.getName == "parboiled-scala_2.10.0-RC1-1.1.3.jar"}
}
addArtifact(artifact in (Compile, assembly), assembly)
Do remember to change the mainClass in assembly.
project/build.properties
sbt.version=0.12.1
project/Build.scala
import sbt._
import Keys._
object ApplicationBuild extends Build {
lazyvalmain = Project(id = "easysprayrestserver",
base = file("."), settings = Project.defaultSettings).settings()
}
project/plugins.sbt
addSbtPlugin("io.spray" % "sbt-revolver" % "0.6.2")
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.0")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.8.5")
Then we can do the command like this
Start the application with default configuration
sbt>re-start
Stop the application
sbt>re-stop
Build the binary file
sbt>assembly
Run the application directly from Java
>java -Dconfig.file=/path/application.conf -jar LocalpointAPI-assembly-0.1.jar
And there is another configuration file.
src/main/resources/application.conf
build.env = ""
build.env = ${?env}
server {
address = "0.0.0.0"
port = 9000
}environment {app1 { server { address = "0.0.0.0" port = 9001 }}
app2 { server { address = "0.0.0.0" port = 9002 }}
}
The application which will use this configuration will be
val config = ConfigFactory.load()
val env = config.getString("build.env")
var serverAddress: String = config.getString("server.address")
var serverPort: Int = config.getInt("server.port")
if (env != null && env != "") {
serverAddress = if (config.getString("environment." + env + ".server.address") != null) config.getString("environment." + env + ".server.address") elseserverAddress
serverPort = if (config.getInt("environment." + env + ".server.port") != 0) config.getInt("environment." + env + ".server.port") elseserverPort
}
newHttpServer(handler) ! Bind(interface = serverAddress, port = serverPort)
Then the command will be
Open the port 9001
sbt>re-start --- -Dbuild.env=app1
Open the port 9002
sbt>re-start --- -Dbuild.env=app2
Open the default port 9000
sbt>re-start
3. How to Write Test
come soon…
4. How to Work with Actor
come soon…
5. How to Work with Logback
come soon…
Tips
1. Eclipse is so slow
I try to download and use eclipse from type safe
http://typesafe.com/stack/downloads/scala-ide
And install the JGit for it
http://download.eclipse.org/egit/updates
References:
spray
http://sillycat.iteye.com/blog/1766558
http://sillycat.iteye.com/blog/1766568
http://sillycat.iteye.com/blog/1767203
http://sillycat.iteye.com/blog/1768065
slick
http://sillycat.iteye.com/blog/1767204
http://sillycat.iteye.com/blog/1767865
Source codes
https://github.com/spray/spray
http://spray.io/documentation/spray-testkit/
https://github.com/spray/spray-template
1. Recall some ideas
These things consist of all the modules we are using.
spray-can, spray-routing, spray-io, spray-http, spray-util, spray-testkit, spray-json
How we deal with HTTP
def receive = {
case HttpRequest(HttpMethods.GET, "/", _, _, _) =>
sender ! index
case HttpRequest(HttpMethods.GET, "/stop", _, _, _) =>
sender ! HttpResponse(entity = "Shutting down in 1 second ...")
context.system.scheduler.scheduleOnce(1 second span, new Runnable { def run() { context.system.shutdown() } })
case HttpRequest(GET, "/server-stats", _, _, _) =>
valclient = sender
(context.actorFor("../http-server") ? HttpServer.GetStats).onSuccess {
casex: HttpServer.Stats => client ! statsPresentation(x)
}
case HttpRequest(GET, "/io-stats", _, _, _) =>
valclient = sender
(IOExtension(context.system).ioBridge() ? IOBridge.GetStats).onSuccess {
case IOBridge.StatsMap(map) => client ! statsPresentation(map)
}
case HttpRequest(HttpMethods.GET, "/event", _, _, _) =>
sender ! ok
}
Spray Routing
class MyService extends Actor with HttpServiceActor {
def receive = handleTimeouts orElse runRoute(myRoute)
def myRoute: Route = `<my-route-definition>`
def handleTimeouts: Receive = {
case Timeout(x: HttpRequest) =>
sender ! HttpResponse(StatusCodes.InternalServerError, "Too late")
} }
The ~ operator was introduced, which connects two routes in a way that allows a second route to get a go at a request if the first route "rejected" it.
Spray-json
Then I can parse the string to AST abstract Syntax Tree(AST).
1.1. String to AST
valjson1 = """{ "streetNumber": "A1", "street" : "Main Street", "city" : "Colombo" }"""
valjson2 = """{ "name" : "John", "age" : 26, "sex" : 0 , "address" : { "streetNumber": "A1", "street" : "Main Street", "city" : "Colombo" }}"""
//string to AST
valaddressAST = json1.asJson //or JsonParser(source)
valpersonAST = json2.asJson
1.2. AST to String
//AST to string
println(addressAST.compactPrint) //or .compactPrint
println(personAST.prettyPrint)
1.3. AST to Object
import AddressJsonProtocol._
//AST 2 Object
val address1 = addressAST.convertTo[Address]
1.4. Object to AST
//Object 2 AST
valaddressAST2 = address1.toJson
Slick
Do with slick and native SQL.
2. Prepare a New Project
I need to add something to build.sbt to make some sbt commands works.
sbt>re-start
sbt>re-stop
sbt>assembly
build.sbt
import AssemblyKeys._
seq(Revolver.settings: _*)
mainClass in assembly := Some("com.sillycat.easysprayrestserver.Boot")
artifact in (Compile, assembly) ~= { art =>
art.copy(`classifier` = Some("assembly"))
}
excludedJars in assembly <<= (fullClasspath in assembly) map { cp =>
cp filter {_.data.getName == "parboiled-scala_2.10.0-RC1-1.1.3.jar"}
}
addArtifact(artifact in (Compile, assembly), assembly)
Do remember to change the mainClass in assembly.
project/build.properties
sbt.version=0.12.1
project/Build.scala
import sbt._
import Keys._
object ApplicationBuild extends Build {
lazyvalmain = Project(id = "easysprayrestserver",
base = file("."), settings = Project.defaultSettings).settings()
}
project/plugins.sbt
addSbtPlugin("io.spray" % "sbt-revolver" % "0.6.2")
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.0")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.8.5")
Then we can do the command like this
Start the application with default configuration
sbt>re-start
Stop the application
sbt>re-stop
Build the binary file
sbt>assembly
Run the application directly from Java
>java -Dconfig.file=/path/application.conf -jar LocalpointAPI-assembly-0.1.jar
And there is another configuration file.
src/main/resources/application.conf
build.env = ""
build.env = ${?env}
server {
address = "0.0.0.0"
port = 9000
}environment {app1 { server { address = "0.0.0.0" port = 9001 }}
app2 { server { address = "0.0.0.0" port = 9002 }}
}
The application which will use this configuration will be
val config = ConfigFactory.load()
val env = config.getString("build.env")
var serverAddress: String = config.getString("server.address")
var serverPort: Int = config.getInt("server.port")
if (env != null && env != "") {
serverAddress = if (config.getString("environment." + env + ".server.address") != null) config.getString("environment." + env + ".server.address") elseserverAddress
serverPort = if (config.getInt("environment." + env + ".server.port") != 0) config.getInt("environment." + env + ".server.port") elseserverPort
}
newHttpServer(handler) ! Bind(interface = serverAddress, port = serverPort)
Then the command will be
Open the port 9001
sbt>re-start --- -Dbuild.env=app1
Open the port 9002
sbt>re-start --- -Dbuild.env=app2
Open the default port 9000
sbt>re-start
3. How to Write Test
come soon…
4. How to Work with Actor
come soon…
5. How to Work with Logback
come soon…
Tips
1. Eclipse is so slow
I try to download and use eclipse from type safe
http://typesafe.com/stack/downloads/scala-ide
And install the JGit for it
http://download.eclipse.org/egit/updates
References:
spray
http://sillycat.iteye.com/blog/1766558
http://sillycat.iteye.com/blog/1766568
http://sillycat.iteye.com/blog/1767203
http://sillycat.iteye.com/blog/1768065
slick
http://sillycat.iteye.com/blog/1767204
http://sillycat.iteye.com/blog/1767865
Source codes
https://github.com/spray/spray
http://spray.io/documentation/spray-testkit/
https://github.com/spray/spray-template
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 467NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 328Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 428Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 376Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 464NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 413Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 330Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 242GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 443GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 320GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 306Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 310Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 285Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 302Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 276NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 254Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 564NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 255Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 356Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 363Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
AndroidAsync.zip,用于Android的异步套接字、HTTP(客户端 服务器)、WebSocket和socket.io库。基于nio,而不是threads.asynchronous socket、http(client server)和android的websocket库。基于nio,而不是线程。
spray-actor-per-request, 使用每个请求模型中的参与者的示例 Spray 应用程序 每个请求的 Spray这个项目提供了一个示例 Spray 应用程序,它使用每个请求模型中的参与者。为什么要为每个HTTP请求启动一个参与者?轻松...
"slick-pg_spray-json_2.10-0.5.2.2.zip"中的Slick-PG版本,结合了Scala的spray-json库,使得JSON数据可以无缝地在数据库和代码之间转换。spray-json是Scala的一个轻量级、快速且易于使用的JSON库,它可以方便地解析...
描述 "spray-cache-spymemcached.zip" 涉及的是一个针对 Spray 框架的缓存扩展,名为 SpyMemcached 后端。Spray 是一个基于 Scala 的高性能、轻量级的 HTTP 和 RESTful 服务构建工具,常用于构建异步、非阻塞的服务...
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
5. **类型安全**:得益于Scala的静态类型系统,spray-template可以在编译时捕获模板错误,避免运行时的意外。 6. **高效性能**:模板在首次渲染后会被编译成高效的Scala代码,从而在后续请求中提供更快的响应速度。...
$ git clone git://github.com/spray/spray-template.git my-project 将目录更改为您的克隆: $ cd 我的项目 启动 SBT: $ sbt 编译一切并运行所有测试: 测试 启动应用程序: 重新开始 浏览到以查看 angular...
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
官方版本,亲测可用
$ git clone https://github.com/Gneotux/pfc-spray.git my-project 将目录更改为您的克隆: $ cd my-project 3(可选)。 使用{DIRECTORY} /src/main/resources/schema.sql中的脚本在postgres中创建数据库,修改...
概要该项目解释了如何使用具有 CORS 支持的 Spray 实现 REST API假设我假设你有经验和你的工作环境准备好使用以下技术/框架: Akka、SBT、CORS、Spray、cURL、Scala、Git要求这篇文章面向那些有 Scala 工作经验并...