
Vercel Functions 是 Vercel 提供的 serverless 服务,作用与 CF worker 类似,能够提供低延时、高可用、弹性的后端服务。Vercel Functions 官方支持 Nodejs 、Go、Python、、Ruby、Edge runtime, 同时社区支持 Bash、Deno、PHP、Rust runtime


Rust 本身具有高性能、内存安全的特点,但仅靠上述优点难以说服习惯使用 Node js 作为后端的开发者们迁移到 Rust,而不同于仅对于请求数做出限制的 CF Worker, Vercel Functions 对于运行时占用的内存、CPU 等资源也有相应限制。相较之下,内存占用少、速度快且基于 tokio 开发的 Rust runtime 就显得眉清目秀了。
Vercel Functions 在 runtime 方面具有相当的灵活性:可以通过 vercel.json 文件指定不同函数的 runtime。
<!-- python runtime vercel.json 示例 -->
{
"$schema": "https://openapi.vercel.sh/vercel.json",
"functions": {
"api/**/*.py": {
"excludeFiles": "{tests/**,__tests__/**,**/*.test.py,**/test_*.py,fixtures/**,__fixtures__/**,testdata/**,sample-data/**,static/**,assets/**}"
}
}
}<!-- rust runtime vercel.json 示例 -->
{
"functions": {
"api/**/*.rs": {
"runtime": "vercel-rust@4.0.9"
}
}
}对于 Rust runtime 而言,还需要配置 Cargo.toml 文件,示例如下
[package]
name = "nextjs_runtime_demo"
version = "0.1.0"
edition = "2021"
publish = false
[dependencies]
tokio = { version = "1", features = ["macros"] }
tracing = { version = "0.1", features = ["log"] }
tracing-subscriber = { version = "0.3", default-features = false, features = [
"fmt",
] }
serde = { version = "1.0.188", features = ["derive"] }
serde_json = { version = "1.0.106", features = ["raw_value"] }
serde_derive = "1.0.188"
rand = "0.8.5"
oorandom = "11.1.3"
vercel_runtime = "1.1.3"
# vercel_runtime = { version = "1.1.0", path = "../../crates/vercel_runtime" }
[[bin]]
name = "rust"
path = "api/rust.rs"以下为 Vercel Function Rust runtime 示例代码:
use serde_json::json;
use vercel_runtime::{run, Body, Error, Request, Response, StatusCode};
#[tokio::main]
async fn main() -> Result<(), Error> {
run(hello).await
}
pub async fn hello(_req: Request) -> Result<Response<Body>, Error> {
Ok(Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "application/json")
.body(
json!({
"message": "你好,世界"
})
.to_string()
.into(),
)?)
}关于 runtime performance,没有找到太好的示例,仅以控制台监测数据作为参考,由下图数据可以明显看出 Rust runtime 在内存占用、冷启动、响应速度方面的巨大优势。






Node runtime 代码如下:
import { Hono } from 'hono'
const app = new Hono()
const welcomeStrings = [
"Hello Hono!",
"To learn more about Hono on Vercel, visit https://vercel.com/docs/frameworks/backend/hono",
]
app.get('/', (c) => {
return c.text(welcomeStrings.join('\n\n'))
})
export default appRust runtime 代码如下:
use serde_json::json;
use vercel_runtime::{run, Body, Error, Request, Response, StatusCode};
#[tokio::main]
async fn main() -> Result<(), Error> {
run(hello).await
}
pub async fn hello(_req: Request) -> Result<Response<Body>, Error> {
Ok(Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "application/json")
.body(
json!({
"message": "你好,世界"
})
.to_string()
.into(),
)?)
}或许 Rust runtime 的生态仍然远不如 Node runtime,但对于追求极限成本、响应速度或是计算密集型功能的开发者来说, Rust runtime 值得一试!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。