NGINX.COM
Web Server Load Balancing with NGINX Plus

在我们系列博文的第一篇第二篇中,我们介绍了 WebAssembly 组件模型的核心机制,并展示了如何使用 WASI 0.2 API 和 wasi/http:proxy world 创建 Wasm 组件。

本文将介绍 FermyonRust 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 上。

Hero image
免费白皮书:
NGINX 企阅版全解析

助力企业用户规避开源治理风险,应对开源使用挑战

关于作者

Timo Stark

Professional Services Engineer

关于 F5 NGINX

F5, Inc. 是备受欢迎的开源软件 NGINX 背后的商业公司。我们为现代应用的开发和交付提供一整套技术。我们的联合解决方案弥合了 NetOps 和 DevOps 之间的横沟,提供从代码到用户的多云应用服务。访问 nginx-cn.net 了解更多相关信息。