- 浏览: 2552956 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
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
Playframework(3)Java Project and Handling asynchronous results
2. Handling asynchronous results
We were able to compute the result to send to the web client directly. This is not always the case: the result may depend of an expensive computation or on a long web service call.
Action should be as fast as possible. (non blocking). We should return a result if we are not yet able to compute, the response should be a promise of a result.
Promise<Result> instead of a normal Result.
Play will then serve this result as soon as the promise is redeemed.
The web client will be blocked while waiting for the response but nothing will be blocked on the server, and server resources can be used to serve other clients.
How to create a Promise<Result>
I am not quite understand this part. Maybe, I will learn it later.
Streaming HTTP responses
According to HTTP 1.1, the server must send the appropriate Content-Length HTTP header along with the response.
public static Result index(){
return ok("Hello World")
}
Play is able to compute the content size for us and generate the appropriate header.
Serving Files
sending back a local file
…snip…
return ok(new java.io.File("/tmp/fileToServe.pdf"));
…snip...
The default Content-Dispostion will be Disposition: attachment; filename=fileToServe.pdf
Chunked Response
Chunked transfer encoding, dynamically-computed content with no content size available.
public static index(){
Chunks<String> chunks = new StringChunks(){
public void onReady(Chunks.Out<String> out){
registerOutChannelSomewhere(out);
}
}
ok(chunks);
}
public void registerOutChannelSomewhere(Chunks.Out<String> out){
out.write("kiko");
out.write("foo");
out.close();
}
HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 Transfer-Encoding: chunked
Comet Sockets and WebSockets
play is able to handle these things. But I will learn them in the future.
3. The template engine
A Play Scala template is a simple text file that contains small blocks of Scala code. Templates can generate any text-based format, such as HTML, XML or CSV.
Templates are compiled as standard Scala functions, following a simple naming convention. If you create a
views/Application/index.scala.html
views.html.Application.index
class that has a render() method.
For example, template:
@(customer: Customer, orders: List[Order])
<h1>Welcome @customer.name!</h1>
<ul>
@for(order <- orders){
<li>@order.getTitle()</li>
}
</ul>
Content html = views.html.Application.index.render(customer, orders);
Escape the special character like this @@.
@customer.getName()! @customer.name! @(customer.getFirstName() + customer.getLastName())!
@{var name= customer.getFirstName() + customer.getLastName(); name}! // multiple statements
Template parameters
A template is like a function, so it needs parameters, which must be declared at the top of the template file:
@(customer: models.Customer, orders: List[models.Order])
@(title: String = "Home") //default value
@(title:String)(body: Html) //several parameters
Iterating
<ul>
@for(p <- products){
<li>@p.getName() ($@p.getPrice())</li>
}
</ul>
If-blocks simply use Scala's standard if statement
@if(items.isEmpty()){
<h1>Nothing to display</h1>
}else{
<h1>@items.size() items!</h1>
}
Declaring Reusable Blocks
We can create reusable code blocks:
@display(product:models.Product) = {
@product.getName() ($@product.getPrice())
}
<ul>
@for(product <- products){
@display(product)
}
</ul>
Comments
@* coments here *@
Escaping
Dynamic content parts are escaped according to the template type's rules(e.g. HTML or XML). If we want to output raw content fragment.
<p>
@Html(article.content)
</p>
Common Template Use Cases
Layout ---- views/main.scala.html
@(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>@title</title>
</head>
<body>
<section class="content">@content</section>
</body>
</html>
Out simple page can use this template views/Application/index.scala.html
@main(title = "Home"){
<h1>Home page</h1>
}
Add a second page-specific content block for a sidebar or breadcrumb trail.
@(title: String)(sidebar: Html)(content: Html)
<!DOCTYPE html>
<head>
<title>@title</title>
</head>
<body>
<section class="content">@content</section>
<section class="sidebar">@sidebar</section>
</body>
</html>
Our page template will be:
@main("Home"){
<h1>Sidebar</h1>
}{
<h1>Home page</h1>
}
Or we can declare the sidebar block separately:
@sidebar = {
<h1>Sidebar</h1>
}
@main("Home")(sidebar) {
<h1>Home page</h1>
}
Tags
views/tags/notice.scala.html
@(level: String = "error") (body: (string) => Html)
@level match{
case "success" =>{
<p class="success">
@body("green")
</p>
}
case "error" => {
<p class="error">
@body("red")
</p>
}
}
When we use the tag:
@import tags._
@notice("error"){ color =>
Oops, something is <span style="color:@color">Wrong</span>
}
References:
http://www.playframework.org/documentation/2.0.4/JavaAsync
http://www.playframework.org/documentation/2.0.4/JavaHome
2. Handling asynchronous results
We were able to compute the result to send to the web client directly. This is not always the case: the result may depend of an expensive computation or on a long web service call.
Action should be as fast as possible. (non blocking). We should return a result if we are not yet able to compute, the response should be a promise of a result.
Promise<Result> instead of a normal Result.
Play will then serve this result as soon as the promise is redeemed.
The web client will be blocked while waiting for the response but nothing will be blocked on the server, and server resources can be used to serve other clients.
How to create a Promise<Result>
I am not quite understand this part. Maybe, I will learn it later.
Streaming HTTP responses
According to HTTP 1.1, the server must send the appropriate Content-Length HTTP header along with the response.
public static Result index(){
return ok("Hello World")
}
Play is able to compute the content size for us and generate the appropriate header.
Serving Files
sending back a local file
…snip…
return ok(new java.io.File("/tmp/fileToServe.pdf"));
…snip...
The default Content-Dispostion will be Disposition: attachment; filename=fileToServe.pdf
Chunked Response
Chunked transfer encoding, dynamically-computed content with no content size available.
public static index(){
Chunks<String> chunks = new StringChunks(){
public void onReady(Chunks.Out<String> out){
registerOutChannelSomewhere(out);
}
}
ok(chunks);
}
public void registerOutChannelSomewhere(Chunks.Out<String> out){
out.write("kiko");
out.write("foo");
out.close();
}
HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 Transfer-Encoding: chunked
Comet Sockets and WebSockets
play is able to handle these things. But I will learn them in the future.
3. The template engine
A Play Scala template is a simple text file that contains small blocks of Scala code. Templates can generate any text-based format, such as HTML, XML or CSV.
Templates are compiled as standard Scala functions, following a simple naming convention. If you create a
views/Application/index.scala.html
views.html.Application.index
class that has a render() method.
For example, template:
@(customer: Customer, orders: List[Order])
<h1>Welcome @customer.name!</h1>
<ul>
@for(order <- orders){
<li>@order.getTitle()</li>
}
</ul>
Content html = views.html.Application.index.render(customer, orders);
Escape the special character like this @@.
@customer.getName()! @customer.name! @(customer.getFirstName() + customer.getLastName())!
@{var name= customer.getFirstName() + customer.getLastName(); name}! // multiple statements
Template parameters
A template is like a function, so it needs parameters, which must be declared at the top of the template file:
@(customer: models.Customer, orders: List[models.Order])
@(title: String = "Home") //default value
@(title:String)(body: Html) //several parameters
Iterating
<ul>
@for(p <- products){
<li>@p.getName() ($@p.getPrice())</li>
}
</ul>
If-blocks simply use Scala's standard if statement
@if(items.isEmpty()){
<h1>Nothing to display</h1>
}else{
<h1>@items.size() items!</h1>
}
Declaring Reusable Blocks
We can create reusable code blocks:
@display(product:models.Product) = {
@product.getName() ($@product.getPrice())
}
<ul>
@for(product <- products){
@display(product)
}
</ul>
Comments
@* coments here *@
Escaping
Dynamic content parts are escaped according to the template type's rules(e.g. HTML or XML). If we want to output raw content fragment.
<p>
@Html(article.content)
</p>
Common Template Use Cases
Layout ---- views/main.scala.html
@(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>@title</title>
</head>
<body>
<section class="content">@content</section>
</body>
</html>
Out simple page can use this template views/Application/index.scala.html
@main(title = "Home"){
<h1>Home page</h1>
}
Add a second page-specific content block for a sidebar or breadcrumb trail.
@(title: String)(sidebar: Html)(content: Html)
<!DOCTYPE html>
<head>
<title>@title</title>
</head>
<body>
<section class="content">@content</section>
<section class="sidebar">@sidebar</section>
</body>
</html>
Our page template will be:
@main("Home"){
<h1>Sidebar</h1>
}{
<h1>Home page</h1>
}
Or we can declare the sidebar block separately:
@sidebar = {
<h1>Sidebar</h1>
}
@main("Home")(sidebar) {
<h1>Home page</h1>
}
Tags
views/tags/notice.scala.html
@(level: String = "error") (body: (string) => Html)
@level match{
case "success" =>{
<p class="success">
@body("green")
</p>
}
case "error" => {
<p class="error">
@body("red")
</p>
}
}
When we use the tag:
@import tags._
@notice("error"){ color =>
Oops, something is <span style="color:@color">Wrong</span>
}
References:
http://www.playframework.org/documentation/2.0.4/JavaAsync
http://www.playframework.org/documentation/2.0.4/JavaHome
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 476NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 337Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 436Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 385Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 479NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 424Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 337Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 248GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 452GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 328GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 314Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 319Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 294Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 312Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 288NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 261Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 574NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 266Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 368Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 371Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
- **异步处理(Asynchronous Handling)**:能够提升服务器的吞吐量,提高响应速度。 #### Play框架的使用 - **设置开发环境**:安装Java开发工具包和Scala编译器。然后下载并设置Play框架环境,可以使用sbt...
SUMMARYPlay for Java shows you how to build Java-based web applications using the Play 2 framework. The book starts by introducing Play through a comprehensive overview example. Then, you'll look at ...
7. **AJAX (Asynchronous JavaScript and XML)** AJAX不是一种单一的技术,而是一组用于创建交互式Web应用的技术集合。它允许网页在不刷新整个页面的情况下与服务器交换数据并更新部分页面内容,提高了用户体验。在...
To start with, we will discuss the details of the Android process model and the Java low-level concurrent framework, delivered by the Android SDK. Next, we will discuss the creation of IntentServices...
AJAX (Asynchronous JavaScript And XML)
Asynchronous Http and WebSocket Client library for Java
ASP.NET MVC with Entity Framework and CSS by Lee Naylor 2016 | ISBN: 1484221362 | English | 608 pages | True PDF | 30 MB This book will teach readers how to build and deploy a fully working example ...
Tackle testable business logic development and asynchronous messaging with an SMTP service Expose enterprise services as a RESTful interface, using Java EE’s JAX-RS framework Implement OAuth ...
Reactive Streams in Java explains how to manage the exchange of stream data across an asynchronous boundary―passing elements on to another thread or thread-pool―while ensuring that the receiving ...
- **Conciseness**: Discussion on Scala's concise syntax, which often results in shorter and more readable code compared to Java. - **Concurrency Models**: Explanation of Scala's support for reactive...
including improved performance due to the Java virtual machine (JVM), easy integration with other Java technologies, and a rich set of APIs for handling HTTP requests. - **Application Architecture*...
The .NET Framework provides three patterns for performing asynchronous operations: Asynchronous Programming Model (APM) pattern Event-based Asynchronous Pattern (EAP) Task-based Asynchronous Pattern ...
在IT领域,异步套接字(Asynchronous Socket)服务器和客户端是网络编程中的核心概念,主要用于构建高效、可扩展的通信系统。本项目提供的代码示例深入探讨了这一技术,帮助开发者理解如何在实际应用中实现异步通信...
lightweight framework for deep reinforcement learning that uses asynchronous gradient descent for optimization of deep neural network controllers. We present asynchronous variants of four standard ...
The Node.js runtime has become a major platform for de- velopers ...level conceptual framework for reasoning about relationships between the execution of asynchronous callbacks in a Node.js application.
To start with, we will discuss the details of the Android process model and the Java low-level concurrent framework, delivered by the Android SDK. Next, we will discuss the creation of IntentServices...