// Make the request
CompletionStage futureResponse =
ws.url(url).setMethod("GET").stream();
CompletionStage bytesReturned = futureResponse.thenCompose(res -> {
Source responseBody = res.getBodyAsSource();
// Count the number of bytes returned
Sink> bytesSum =
Sink.fold(0L, (total, bytes) -> total + bytes.length());
return responseBody.runWith(bytesSum, materializer);
});
也可以将将返回体流化到另一个目的地,比如一个文件
File file = File.createTempFile("stream-to-file-", ".txt");
OutputStream outputStream = java.nio.file.Files.newOutputStream(file.toPath());
// Make the request
CompletionStage futureResponse =
ws.url(url).setMethod("GET").stream();
CompletionStage downloadedFile = futureResponse.thenCompose(res -> {
Source responseBody = res.getBodyAsSource();
// The sink that writes to the output stream
Sink.Done>> outputWriter =
Sink.foreach(bytes -> outputStream.write(bytes.toArray()));
// materialize and run the stream
CompletionStage result = responseBody.runWith(outputWriter, materializer)
.whenComplete((value, error) -> {
// Close the output stream whether there was an error or not
try { outputStream.close(); }
catch(IOException e) {}
})
.thenApply(v -> file);
return result;
});
另外一种是将结果返回到Action中
// Make the request
CompletionStage futureResponse = ws.url(url).setMethod("GET").stream();
CompletionStage result = futureResponse.thenApply(response -> {
Source body = response.getBodyAsSource();
// Check that the response was successfulif (response.getStatus() == 200) {
// Get the content type
String contentType =
Optional.ofNullable(response.getHeaders().get("Content-Type"))
.map(contentTypes -> contentTypes.get(0))
.orElse("application/octet-stream");
// If there's a content length, send that, otherwise return the body chunked
Optional contentLength = Optional.ofNullable(response.getHeaders()
.get("Content-Length"))
.map(contentLengths -> contentLengths.get(0));
if (contentLength.isPresent()) {
return ok().sendEntity(new HttpEntity.Streamed(
body,
Optional.of(Long.parseLong(contentLength.get())),
Optional.of(contentType)
));
} else {
return ok().chunked(body).as(contentType);
}
} else {
returnnew Result(Status.BAD_GATEWAY);
}
});
Note: 如果你手动创建WSClient那么一定要调用client.close()方法进去清理。每个clinet会创建自己定线程池,如果你没有进行管理或者创建了过多的客户端,你会耗尽线程或文件句柄——最终会得到类似“Unable to create new native thread” 或 “too many open files” 的错误。
下面是一个例子
import akka.stream.Materializer;
import akka.stream.javadsl.*;
import akka.util.ByteString;
import play.mvc.Results;
// Set up the client config (you can also use a parser here):
// play.api.Configuration configuration = ... // injection
// play.Environment environment = ... // injection
WSClient customWSClient = play.libs.ws.ahc.AhcWSClient.create(
play.libs.ws.ahc.AhcWSClientConfigFactory.forConfig(
configuration.underlying(),
environment.classLoader()),
null, // no HTTP caching
materializer);
// Set up Akka
String name = "wsclient";
ActorSystem system = ActorSystem.create(name);
ActorMaterializerSettings settings = ActorMaterializerSettings.create(system);
ActorMaterializer materializer = ActorMaterializer.create(settings, system, name);
// Read in config file from application.conf
Config conf = ConfigFactory.load();
WSConfigParser parser = new WSConfigParser(conf, ClassLoader.getSystemClassLoader());
AhcWSClientConfig clientConf = AhcWSClientConfigFactory.forClientConfig(parser.parse());
// Start up asynchttpclient
final DefaultAsyncHttpClientConfig asyncHttpClientConfig = new AhcConfigBuilder(clientConf).configure().build();
final DefaultAsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(asyncHttpClientConfig);
// Create a new WS client, andthenclose the client.
WSClient client = new AhcWSClient(asyncHttpClient, materializer);
client.close();
system.terminate();
Play WS对body提供了丰富的支持。play.libs.ws.WSBodyWritables提供方法将WSRequest中的JsonNode或XML这样的输入转化为ByteString or Source,相应的play.libs.ws.WSBodyReadables从WSResponse中读取 ByteString or Source[ByteString, _]然后返回一个合适的类型(JsValue或者XML)。WSRequest和WSResponse中提供了默认的实现供你使用,但是你也可以根据需要通过response.getBody(myReadable()) 和request.post(myWritable(data))使用自定义的类型。在使用自定义的类库时会非常使用i.e.你也许想通过STaX API将XML流化。
我们都晓得java实现线程2种方式,一个是继承Thread,另一个是实现Runnable。
模拟窗口买票,第一例子继承thread,代码如下
package thread;
public class ThreadTest {
public static void main(String[] args) {
Thread1 t1 = new Thread1(
#include<iostream>
using namespace std;
//辅助函数,交换两数之值
template<class T>
void mySwap(T &x, T &y){
T temp = x;
x = y;
y = temp;
}
const int size = 10;
//一、用直接插入排
对日期类型的数据进行序列化和反序列化时,需要考虑如下问题:
1. 序列化时,Date对象序列化的字符串日期格式如何
2. 反序列化时,把日期字符串序列化为Date对象,也需要考虑日期格式问题
3. Date A -> str -> Date B,A和B对象是否equals
默认序列化和反序列化
import com
1. DStream的类说明文档:
/**
* A Discretized Stream (DStream), the basic abstraction in Spark Streaming, is a continuous
* sequence of RDDs (of the same type) representing a continuous st
ReplayingDecoder是FrameDecoder的子类,不熟悉FrameDecoder的,可以先看看
http://bylijinnan.iteye.com/blog/1982618
API说,ReplayingDecoder简化了操作,比如:
FrameDecoder在decode时,需要判断数据是否接收完全:
public class IntegerH
1.js中用正则表达式 过滤特殊字符, 校验所有输入域是否含有特殊符号function stripscript(s) { var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?]"
经常在写shell脚本时,会碰到要以另外一个用户来执行相关命令,其方法简单记下:
1、执行单个命令:su - user -c "command"
如:下面命令是以test用户在/data目录下创建test123目录
[root@slave19 /data]# su - test -c "mkdir /data/test123"