更新时间:2025-08-18 gmt 08:00
配置函数的流式返回-j9九游会登录
函数流式返回概述
为满足当前web应用及ai应用在实时数据传输和大报文传输方面的需求,函数支持配置流式返回开关,将函数的响应报文以http流式传输的方式返回给客户端。
采用流式返回具有以下优势:
- 支持更大规模的响应报文(最大可达200m)。
- 由于流式传输无需一次性传输全部报文,可在函数代码中分批处理和传输数据,有效降低内存占用。
- 通过流式传输可实现更快的首字节响应时间。
适用场景包括:
- 大文件或大数据集的处理场景(如图片、视频处理等)。
- 实时数据处理场景(例如ai大模型应用需使用server-sent events (sse) 协议进行数据传输),需要快速返回响应数据,而非一次性返回全部数据。
约束与限制
- 流式返回配置当前支持“西南-贵阳一”和“华北-北京四”区域使用。
- 仅容器镜像函数、定制运行时函数和http函数支持配置流式返回。
- 流式返回最大支持响应报文大小为200mb。
- 流式返回仅支持同步调用,执行超时时间限制最大300s。
配置流式返回
- 登录,在左侧的导航栏选择“函数 > 函数列表”。
- 单击函数的名称,进入函数详情页。在“设置”页签下选择“高级设置”。
- 开启“流式返回”,单击“保存”。
图1 开启流式返回
编写流式返回函数代码
以下为容器镜像函数、http函数和定制运行时函数的代码示例。
参考使用容器镜像创建函数完成容器镜像函数创建,并开启流式返回。请注意,函数超时时间配置需控制在300s以内,否则将导致函数保存失败。
为了确保函数能够正确返回流式数据,在函数的响应体生成过程中,建议分批次写入流式数据,以避免内存浪费。以下提供一个简单的java springboot应用返回流式数据的示例:
@springbootapplication
@restcontroller
public class springbootdemohelloworldapplication {
private executorservice executor = executors.newcachedthreadpool();
public static void main(string[] args) {
springapplication.run(springbootdemohelloworldapplication.class, args);
}
/**
* stream response
* @return
*/
@postmapping(value = "/invoke")
public responseentity invoke(@requestbody map body) {
responsebodyemitter emitter = new responsebodyemitter();
executor.submit(() -> {
try {
emitter.send("hello \n", mediatype.text_event_stream);
emitter.send("world \n", mediatype.text_event_stream);
emitter.complete();
} catch (exception ex) {
emitter.completewitherror(ex);
}
});
httpheaders responseheaders = new httpheaders();
responseheaders.setcontenttype(mediatype.text_event_stream);
return new responseentity(emitter, responseheaders, httpstatus.ok);
}
}
参考创建http函数完成http函数创建,并开启流式返回。请注意,函数超时时间配置需控制在300s以内,否则将导致函数保存失败。
http函数的示例代码可参考容器镜像函数示例代码。
定制运行时函数需调用http://$runtime_api_addr/v1/runtime/invocation/response/$request_id的post方法返回流式数据。以下为一个简单的shell类型bootstrap示例:
#!/bin/sh
set -o pipefail
#processing requests loop
while true
do
headers="$(mktemp)"
# get an event
event_data=$(curl -ss -ld "$headers" -x get "http://$runtime_api_addr/v1/runtime/invocation/request")
# get request id from response header
request_id=$(grep -fi x-cff-request-id "$headers" | tr -d '[:space:]' | cut -d: -f2)
if [ -z "$request_id" ]; then
continue
fi
# send streamdata file content back to client
curl -x post "http://$runtime_api_addr/v1/runtime/invocation/response/$request_id" -h "content-type:application/octet-stream" --data-binary "@code/streamdata.txt"
done
测试流式返回函数
- 在函数详情页的“代码”页签下,单击“测试”,弹出“配置测试事件”弹窗。
- 选择“空白模板”,无需修改单击“创建”。
- 选择2创建的测试事件,再次单击“测试”。
- 函数执行成功后,将自动启动下载,下载文件名为此次请求的id,文件内容为此次请求的返回值。
图2 文件下载
相关文档
意见反馈
文档内容是否对您有帮助?
提交成功!非常感谢您的反馈,我们会继续努力做到更好!
您可在查看反馈及问题处理状态。
系统繁忙,请稍后重试
如您有其它疑问,您也可以通过华为云社区问答频道来与我们联系探讨