在我们系列博文的第一篇和第二篇中,我们介绍了 WebAssembly 组件模型的核心机制,并展示了如何使用 WASI 0.2 API 和 wasi/http:proxy world 创建 Wasm 组件。
本文将介绍 Fermyon 的 Rust Spin SDK,并创建一个可托管在 NGINX Unit 上的 Wasm 组件。
Spin SDK 将大量的手动工作整合到易于使用的 API 中,提供了出色的开发人员体验。本文主要侧重于 Rust,如果您希望详细了解其他语言 SDK,请参阅官方文档。
首先,使用 cargo new 新建一个 Rust 库。这将在我们当前工作目录的子目录 test-spin-component 下创建一个新的库项目。
$ cargo new --lib test-spin-component
$ cd test-spin-component
运行以下命令,将最新版本的“spin-sdk”和“anyhow”(Flexible Error Types 和 Spin SDK 的依赖项)crate 添加到项目中:
$ cargo add spin-sdk anyhow
在实现实际功能之前,我们必须修改 Cargo.toml 文件。使用所选的编辑器打开 Cargo.toml,并在现有 Cargo.toml 文件底部添加以下内容。
[lib]
crate-type = ["cdylib"]
[package.metadata.component]
package = "component:test-component"
proxy = true
[package.metadata.component.dependencies]
接下来,将 src/lib.rs 文件的内容替换为以下代码:
use spin_sdk::http::{IntoResponse, Request, Response};
use spin_sdk::http_component;
#[http_component]
fn handle_hello_world(_req: Request) -> anyhow::Result<impl IntoResponse>
{
let body_string = String::from("Hello, this is a Wasm Component using Spin SDK");
Ok(Response::builder()
.status(200)
.header("Content-Type", "text/plain")
.header("Content-Lenght", body_string.len().to_string())
.body(body_string)
.build())
}
使用 cargo component 将 Rust 库编译为 Wasm 组件:
$ cargo component build --release
要在 NGINX Unit 上运行 Wasm 组件,启动 Unit 并使用此初始配置。
备注
确保使用绝对路径指向 Wasm 组件。
{
"listeners": {
"127.0.0.1:8085": {
"pass": "applications/my-spin-component"
}
},
"applications": {
"my-spin-component": {
"type": "wasm-wasi-component",
"component": "target/wasm32-wasi/release/test_spin_component.wasm"
}
}
}
由于我们刚刚创建的 Wasm 组件使用了 wasi:http/proxy 定义的请求和响应接口,因此可以轻松将其部署到 NGINX Unit 上。
"This blog post may reference products that are no longer available and/or no longer supported. For the most current information about available F5 NGINX products and solutions, explore our NGINX product family. NGINX is now part of F5. All previous NGINX.com links will redirect to similar NGINX content on F5.com."