尧图精选

Rust 服务端函数实战:基于 Vercel Runtime 构建 Hello World 示例

🕒 发布时间:2026/9/18 14:25:41 📁 来源:尧图网络
Rust 服务端函数实战基于 Vercel Runtime 构建 Hello World 示例【免费下载链接】examplesEnjoy our curated collection of examples and solutions. Use these patterns to build your own robust and scalable applications.项目地址: https://gitcode.com/GitHub_Trending/examples1/examples本篇文章围绕开源仓库 rust/hello-world 目录中的 Rust 无服务器函数示例展开讲解如何在 Vercel 平台用 Rust 编写多个具备不同能力的 HTTP 端点基础 JSON 响应、服务端事件流式输出、CPU 密集型基准测试等。读完本文你将掌握vercel_runtime的接入方式、Cargo.toml多二进制配置方法以及本地开发与部署验证的完整流程。项目概览一个 Rust 无服务器函数示例rust/hello-world是一个面向 Vercel 平台的最小可运行示例核心目标是演示Rust 服务端函数的编写与组织方式。与常见的单入口服务不同该示例在同一个 Cargo 工程内声明了多个独立的二进制binary每个二进制对应一个 API 端点各自展示一种能力端点源码文件能力/api/simpleapi/simple.rs基础 JSON 响应/api/streamingapi/streaming.rsSSE 流式响应/api/realistic-math-benchapi/realistic-math-bench.rs数学运算基准测试/api/slower-benchapi/slower-bench.rs复杂服务端渲染基准测试仓库根目录还提供了一个深色风格的索引页 index.html罗列上述四个端点并附带简短说明方便部署后快速导航与验证。工程结构与依赖解析目录布局rust/hello-world/ ├── api/ │ ├── simple.rs # 基础 JSON handler │ ├── streaming.rs # SSE 流式响应 handler │ ├── realistic-math-bench.rs # 数学基准测试 handler │ └── slower-bench.rs # 复杂 SSR 基准测试 handler ├── Cargo.toml # 依赖与多二进制配置 ├── Cargo.lock # 锁定依赖版本 ├── README.md # 示例说明文档 └── index.html # 端点导航索引页Cargo.toml核心配置逐项说明Cargo.toml 是整个工程的关键配置文件其要点如下[package] name vercel-rust-hello-world version 0.1.0 edition 2024 [dependencies] vercel_runtime { version 2.4, features [axum] } tokio { version 1, features [full] } hyper { version 1, features [full] } http-body-util 0.1 tokio-stream 0.1 chrono { version 0.4, features [serde] } serde { version 1.0, features [derive] } serde_json 1.0 rand 0.9vercel_runtime官方提供的 Rust 运行时适配库启用axumfeature 后可直接复用 axum 生态的请求/响应类型四个 handler 统一通过它暴露为 HTTP 服务。tokio异步运行时开启fullfeatures 获得完整的 I/O、定时器与同步原语能力流式端点依赖其定时器与mpsc通道。hyper底层 HTTP 实现版本 1配合http-body-util的StreamBody构造流式响应体。tokio-stream将tokio::sync::mpsc::Receiver包装为Stream供流式响应使用。chrono、serde、serde_json、rand分别用于时间格式化、序列化、JSON 生成与随机数simple端点用rand随机挑选起始宝可梦。关键点在于多二进制声明——每个 handler 都必须通过[[bin]]显式注册且name必须唯一# Each handler has to be specified as [[bin]] # Note that you need to provide unique names for each binary: [[bin]] name simple path api/simple.rs [[bin]] name streaming path api/streaming.rs [[bin]] name realistic-math-bench path api/realistic-math-bench.rs [[bin]] name slower-bench path api/slower-bench.rs此外工程针对基准测试场景配置了激进的发布优化策略[profile.release] codegen-units 1 lto fat opt-level 3codegen-units 1与lto fat让编译器进行全程序链接时优化opt-level 3开启最高级别优化——这些配置直接服务于两个基准测试端点对 CPU 性能的测量需求也说明该示例除了教学用途外还被设计为可复现的性能对照实验。四个端点的源码级剖析1./api/simple基础 JSON 响应api/simple.rs 是理解vercel_runtime用法的最小模板use rand::prelude::IndexedRandom; use serde_json::{Value, json}; use vercel_runtime::{Error, Request, run, service_fn}; #[tokio::main] async fn main() - Result(), Error { let service service_fn(handler); run(service).await } pub async fn handler(_req: Request) - ResultValue, Error { let starter choose_starter(); Ok(json!({ message: format!(I choose you, {}!, starter), })) } pub fn choose_starter() - String { let pokemons [Bulbasaur, Charmander, Squirtle, Pikachu]; let starter pokemons.choose(mut rand::rng()).unwrap(); starter.to_string() }入口模式固定为#[tokio::main]异步main→service_fn(handler)包装处理函数 →run(service)启动服务。handler接收vercel_runtime::Request返回可直接 JSON 序列化的serde_json::Value运行时自动完成序列化与响应组装。业务逻辑非常简单用rand从四个初始宝可梦中随机选一个并返回 JSON 消息用于验证最基本的请求-响应链路。2./api/streamingSSE 流式响应api/streaming.rs 演示如何在 Rust 无服务器函数中实现实时数据推送是四个端点中技术含量最高的一例use hyper::body::{Bytes, Frame}; use tokio::time::Duration; use vercel_runtime::{AppState, Error, Request, Response, ResponseBody, service_fn}; async fn handler(_req: Request, state: AppState) - ResultResponseResponseBody, Error { let log_context state.log_context; log_context.info(Starting streaming response); use tokio::sync::mpsc; let (tx, rx) mpsc::channel(10); tokio::spawn(async move { for i in 1..10 { tokio::time::sleep(Duration::from_millis(500)).await; log_context.debug(format!(Sending count: {}, i)); let data format!(Count: {}\n, i); if tx.send(Ok(Frame::data(Bytes::from(data)))).await.is_err() { log_context.warn(Client disconnected during streaming); break; } } log_context.info(Streaming completed); }); let stream tokio_stream::wrappers::ReceiverStream::new(rx); let body http_body_util::StreamBody::new(stream); Ok(Response::builder() .header(content-type, text/event-stream) .header(cache-control, no-cache) .header(connection, keep-alive) .header(transfer-encoding, chunked) .body(body.into())?) }实现链路可拆解为四步取运行时上下文handler 签名带state: AppState从中取得log_context用于打印不同级别的日志info/debug/warn这也是vercel_runtime提供的可观测能力。生产者任务tokio::spawn启动后台任务每 500ms 向mpsc通道写入一条Count: N数据当客户端断开导致发送失败时记录警告并提前退出循环。流式适配用tokio_stream::wrappers::ReceiverStream把通道接收端转成Stream再交给http_body_util::StreamBody组装为流式响应体。SSE 响应头设置text/event-stream、no-cache、keep-alive、chunked等头确保客户端能按事件流持续接收。3./api/realistic-math-benchCPU 密集基准测试api/realistic-math-bench.rs 模拟真实世界中混合的 CPU 计算负载依次执行四类运算整数算术与位运算1000 万次循环包含wrapping_mul、异或、左移以及 LCG线性同余伪随机递推。数组排序与求和构造 100 个各含 10000 个元素的数组使用sort_unstable排序后直接循环求和源码注释特别说明Direct loop is faster than iterator for this pattern。字符串哈希对 100 万个数字做 FNV 风格滚动哈希用栈上定长数组[0i32; 10]代替Vec以避免堆分配。质数统计100000 以内用埃拉托斯特尼筛法统计质数个数。为避免编译器把无用计算结果整体优化掉所有结果都通过std::hint::black_box包裹见 api/realistic-math-bench.rs。最终以 HTML 页面形式渲染出整数结果、排序完成数、字符串哈希值与质数数量并附带服务端渲染时间。4./api/slower-bench复杂服务端渲染基准测试api/slower-bench.rs 构造了一个远比上一个端点昂贵的渲染任务用于对比复杂 SSR 组件的计算成本数据生成计算 500000 以内的全部质数、生成 200 项斐波那契数列再构造 150 个 Section、每个 Section 含 60 个带嵌套元数据时间戳、哈希、复杂度、额外计算的 Item——总计约 9000 条嵌套数据。渲染管线将上述数据拼装为 5MB 级预分配的 HTML 字符串包含质数网格、斐波那契序列卡片、Item 卡片及 300 项阶乘附加计算最后同样用black_box防止优化。应用场景该端点主要用于测量大量数据结构构建 字符串拼接 HTML 渲染这类服务端渲染瓶颈配合上一端点可评估不同负载形态下 Rust 的响应速度。本地开发与运行验证原文档给出的开发流程如下按序执行即可完成从零到本地运行的闭环。克隆仓库git clone https://github.com/vercel/examples.git cd examples/rust/hello-world在本仓库GitHub_Trending/examples1/examples中对应目录为 rust/hello-world可直接进入该目录操作。安装 Rust 工具链若本机尚未安装 Rust使用官方脚本安装curl --proto https --tlsv1.2 -sSf https://sh.rustup.rs | sh安装完成后cargo build会依据 Cargo.toml 与 Cargo.lock 拉取并锁定依赖版本其中锁文件固定了vercel_runtime、axum 0.8.7、hyper 1.x等具体版本保证构建可复现。本地测试安装 Vercel CLI 后在项目目录启动本地开发服务vc devvc dev会读取各api/*.rs端点并按 Vercel 的函数路由约定把它们暴露为本地 HTTP 服务。启动后即可访问http://localhost:3000/— 索引页index.htmlhttp://localhost:3000/api/simple— JSON 响应http://localhost:3000/api/streaming— SSE 流式输出每 500ms 追加一条计数http://localhost:3000/api/realistic-math-bench— 数学基准测试结果页http://localhost:3000/api/slower-bench— 复杂渲染基准测试结果页前提是本地已具备完整的 Rust 工具链含cargo因为vc dev需要编译上述四个二进制目标。与仓库中其他 Rust 示例的关系在仓库 rust 目录下除本示例外还有三个 Rust 相关示例可对照学习rust/axum基于 axum 框架的更完整服务端函数示例rust/websocketWebSocket 长连接示例rust/wait-until演示 VercelwaitUntil能力在 Rust 中的使用。hello-world适合作为入门第一站先通过simple与streaming掌握vercel_runtime的基本接入与流式响应写法再通过两个基准端点理解 Rust 在 CPU 密集与复杂渲染场景下的工程化写法最后可向上述进阶示例延伸。小结rust/hello-world虽然名为Hello World但它覆盖了 Rust 无服务器函数的完整要素vercel_runtime的最小接入模板、Cargo.toml中多二进制[[bin]]的正确组织方式、基于tokiohyper的 SSE 流式实现以及面向性能测量的 release 优化配置。无论你是想快速在 Vercel 上跑通第一个 Rust 函数还是需要一份可复现的 Rust 服务端性能基准骨架都可以直接以 rust/hello-world 为起点。【免费下载链接】examplesEnjoy our curated collection of examples and solutions. Use these patterns to build your own robust and scalable applications.项目地址: https://gitcode.com/GitHub_Trending/examples1/examples创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
上一篇/下一篇内容由系统自动关联 返回资讯列表 →