FrameworkBenchmarks 中的 EmbedIO(C)基准测试:基于 .NET 9 的 Plaintext 与 JSON 测试实现解析
FrameworkBenchmarks 中的 EmbedIO(C#)基准测试:基于 .NET 9 的 Plaintext 与 JSON 测试实现解析
本指南以 TechEmpower FrameworkBenchmarks 仓库中 frameworks/CSharp/embedio/README.md 为核心文档,系统讲解 EmbedIO 这一 C# 内嵌 Web 服务器在 TFB 基准套件中的接入方式:包括其技术栈选型(C# 13.0 + .NET 9)、两个测试端点(Plaintext 与 JSON)的实现源码、项目文件与 Docker 构建流程,以及 TFB 工具链对这两个测试类型的验证机制。读完本文,你将能够理解 EmbedIO 测试实现每一行代码的含义、如何构建与验证该测试,并能据此为其他 C# 框架编写同类基准测试。
测试概览:技术栈与基础设施版本
根据 EmbedIO 测试 README 的说明,该测试运行在 Linux 环境,其基础设施版本如下:
- 语言:C# 13.0(
LangVersion在 Benchmarks.csproj 中显式指定为13.0) - 平台:.NET 9(
TargetFramework为net9.0) - Web 服务器:EmbedIO(NuGet 包版本
3.5.2)
从 Benchmarks.csproj 可以看到完整的项目配置:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<LangVersion>13.0</LangVersion>
<AssemblyTitle>EmbedIO Benchmarks</AssemblyTitle>
<Description>Test suite to be executed with TechEmpower FrameworkBenchmarks.</Description>
<StartupObject>Benchmarks.Program</StartupObject>
<OutputType>Exe</OutputType>
<ServerGarbageCollection>true</ServerGarbageCollection>
<TieredCompilation>false</TieredCompilation>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EmbedIO" Version="3.5.2" />
</ItemGroup>
</Project>
两个值得注意的运行时调优项:
ServerGarbageCollection=true:启用服务器 GC 模式,适用于高并发、多请求的服务端场景,可在高吞吐下获得更平稳的 GC 行为;TieredCompilation=false:关闭分层编译,避免预热阶段的分层 JIT 对基准测试造成不稳定影响。
测试端点与响应要求
README 明确指出该测试包含两个端点,均指向同一实现文件 Benchmarks/Program.cs:
| 测试类型 | 路由 | 期望响应 |
|---|---|---|
| Plaintext | /plaintext |
Hello, World!,Content-Type: text/plain |
| JSON | /json |
{"message":"Hello, World!"},Content-Type: application/json |
这两个路由与 benchmark_config.json 中的 plaintext_url、json_url 字段一一对应,TFB 元数据解析器(toolset/utils/metadata.py)还会对 URL 做合法性校验——json_url 必须至少 5 个字符、plaintext_url 必须至少 10 个字符,并且都必须以 / 开头。
核心实现逐行解读
Benchmarks/Program.cs 是整个测试的唯一业务实现文件。它使用 WebServer 构建器链式配置,完整源码核心逻辑如下:
using var server = new WebServer(o => o
.WithUrlPrefix("http://+:8080/")
.WithMode(HttpListenerMode.EmbedIO))
.PreferNoCompressionFor("text/*")
.WithAction("/plaintext", HttpVerbs.Get, async (ctx) =>
{
var bytes = Encoding.UTF8.GetBytes("Hello, World!");
ctx.Response.ContentType = "text/plain";
ctx.Response.ContentEncoding = Encoding.UTF8;
ctx.Response.ContentLength64 = bytes.Length;
await ctx.Response.OutputStream.WriteAsync(bytes, 0, bytes.Length);
})
.WithAction("/json", HttpVerbs.Get, async (ctx) =>
{
var data = new JsonResult() { Message = "Hello, World!" };
var serialized = Swan.Formatters.Json.Serialize(data);
var bytes = Encoding.UTF8.GetBytes(serialized);
ctx.Response.ContentType = "application/json";
ctx.Response.ContentEncoding = Encoding.UTF8;
ctx.Response.ContentLength64 = bytes.Length;
await ctx.Response.OutputStream.WriteAsync(bytes, 0, bytes.Length);
});
服务器配置要点
WithUrlPrefix("http://+:8080/"):监听所有网卡接口的 8080 端口。TFB 工具链正是通过 benchmark_config.json 中的"port": 8080得知服务端口,并以http://<server_host>:8080为基准 URL 发起验证请求(见 toolset/benchmark/framework_test.py)。WithMode(HttpListenerMode.EmbedIO):选用 EmbedIO 自有的轻量 HTTP 监听模式,而非依赖操作系统HttpListener,这是实现内嵌高并发服务器的关键。PreferNoCompressionFor("text/*"):对text/*类型的响应关闭压缩。Plaintext 测试追求最小响应体积,压缩反而会引入额外开销并放大响应延迟。WithAction(route, HttpVerbs.Get, handler):以“路由 + HTTP 动词 + 异步处理器”的方式注册端点,是 EmbedIO 声明式路由的核心 API。
手动设置响应头:为基准而做的取舍
两个处理器都手动完成以下三件事,这是为匹配 TFB 验证规则所做的刻意设计:
- 将响应体预编码为
byte[](而非直接写入字符串),避免框架内部的重复编码; - 显式设置
ContentType与ContentEncoding; - 设置
ContentLength64(固定Content-Length头)。
TFB 的响应头验证逻辑(toolset/test_types/verifications.py)要求响应必须携带 Server、Date、Content-Type 以及 Content-Length 或 Transfer-Encoding 头;其中 Content-Type 还必须是正则 ^text/plain(; ?charset=(UTF|utf)-8)?$ 或 ^application/json(; ?charset=(UTF|utf)-8)?$ 所允许的形式。ContentLength64 的设置保证了 Content-Length 头存在且精确。
JSON 序列化:使用 Swan 序列化器
JSON 端点定义了内部数据结构:
public class JsonResult
{
public string Message { get; set; }
}
序列化调用 Swan.Formatters.Json.Serialize(data)。Swan 是 EmbedIO 项目(unosquare/embedio)自带的基础工具库,选择它而非 System.Text.Json,避免了额外依赖、保持了基准测试的“原始/轻量”定位。TFB 的 JSON 验证器(toolset/test_types/verifications.py)会忽略大小写和引号风格,检查响应 JSON 是否为包含 message: "hello, world!" 的对象,因此 {"message":"Hello, World!"} 恰好满足要求。
进程生命周期与退出控制
private static readonly ManualResetEvent WaitEvent = new(false);
// 在 Main 中:
Logger.UnregisterLogger<ConsoleLogger>();
AppDomain.CurrentDomain.ProcessExit += (_, __) => WaitEvent.Set();
await server.RunAsync();
WaitEvent.WaitOne();
return 0;
Logger.UnregisterLogger<ConsoleLogger>():关闭 Swan 默认控制台日志输出,避免基准测试期间不必要的 I/O 开销;ProcessExit事件配合ManualResetEvent:保证容器收到终止信号时进程能及时退出,便于 TFB 工具链回收容器资源。
Docker 构建:多阶段、自包含发布
embedio.dockerfile 采用经典的多阶段构建:
FROM mcr.microsoft.com/dotnet/sdk:9.0-alpine AS build
WORKDIR /source
# copy csproj and restore as distinct layers
COPY Benchmarks/*.csproj .
RUN dotnet restore -r linux-musl-x64
# copy and publish app and libraries
COPY Benchmarks/ .
RUN dotnet publish -c release -o /app -r linux-musl-x64 --no-restore --self-contained
# final stage/image
FROM mcr.microsoft.com/dotnet/runtime-deps:9.0-alpine
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["./Benchmarks"]
EXPOSE 8080
关键点:
- 先复制
.csproj再dotnet restore:充分利用 Docker 分层缓存,依赖未变化时无需重新拉取 NuGet 包; -r linux-musl-x64 --self-contained:面向 Alpine(musl libc)自包含发布,最终镜像使用runtime-deps(不含 SDK 的运行时依赖镜像),显著减小镜像体积;ENTRYPOINT ["./Benchmarks"]:直接执行发布产物;EXPOSE 8080:与WithUrlPrefix("http://+:8080/")及配置中的端口保持一致。
TFB 工具链在构建测试时(toolset/utils/docker_helper.py),会以测试目录为构建上下文、以 embedio.dockerfile 为构建文件,将镜像打上 techempower/tfb.test.embedio 标签,并注入 BENCHMARK_ENV、TFB_TEST_NAME、TFB_TEST_DATABASE 等构建参数。
元数据配置:benchmark_config.json 与 config.toml
benchmark_config.json
benchmark_config.json 是 TFB 元数据系统读取的核心配置文件:
{
"framework": "embedio",
"tests": [{
"default": {
"plaintext_url": "/plaintext",
"json_url": "/json",
"port": 8080,
"approach": "Realistic",
"classification": "Fullstack",
"database": "None",
"framework": "EmbedIO",
"language": "C#",
"orm": "Raw",
"platform": ".NET",
"webserver": "EmbedIO",
"os": "Linux",
"database_os": "Linux",
"display_name": "EmbedIO",
"notes": ""
}
}]
}
这些字段会被 toolset/utils/metadata.py 的 validate_test 按 schema 校验:
approach只能是Realistic或Stripped;classification只能是Fullstack、Micro、Platform;database: "None"表示无需数据库——Plaintext 与 JSON 都是无数据库测试类型(toolset/test_types/plaintext/plaintext.py 与 toolset/test_types/json/json.py 中requires_db均为False);orm: "Raw"表示不使用 ORM(该测试本就不涉及数据库访问);os/database_os仅允许Linux/Windows,本测试面向 Linux。
config.toml
config.toml 是同一元数据信息的 TOML 表达,供现代工具链读取:
[framework]
name = "embedio"
[main]
urls.plaintext = "/plaintext"
urls.json = "/json"
approach = "Realistic"
classification = "Fullstack"
database = "None"
database_os = "Linux"
os = "Linux"
orm = "Raw"
platform = ".NET"
webserver = "EmbedIO"
versus = "None"
两份配置保持了完全一致的语义,其中 urls.plaintext / urls.json 直接对应 README 中声明测试路径的“Paths & Source for Tests”小节。
TFB 如何验证与压测这两个端点
验证阶段(verify mode)
当执行 tfb --mode verify --test embedio(参见 toolset/scaffolding/README.md 的验证流程说明)时,工具链会对两个端点逐一验证:
- Plaintext(toolset/test_types/plaintext/plaintext.py):发送带
Accept: text/plain,...头的请求,要求响应体(忽略大小写后)包含hello, world!,并校验 200 状态码与响应头; - JSON(toolset/test_types/json/json.py):发送带
Accept: application/json,...头的请求,将响应体解析为 JSON,通过verify_helloworld_object检查message字段是否为hello, world!。
验证器还会执行“二次请求防缓存”检查:间隔 3 秒再次请求,若两次 Date 头相同则判定失败(toolset/test_types/verifications.py)。
压测阶段(benchmark mode)
压测使用 wrk:
- Plaintext 采用
pipeline.sh+pipeline.lua,使用管道深度 16(pipeline: 16,见 toolset/test_types/plaintext/plaintext.py),即单连接内批量流水线发送请求,以测出极简响应路径的极限吞吐; - JSON 采用
concurrency.sh,按配置的并发层级逐级加压(toolset/test_types/json/json.py)。
两种压测均先跑 primer(5 秒、8 并发)预热,再跑 warmup,最后才是正式分档测量(见 toolset/wrk/pipeline.sh 与 toolset/wrk/concurrency.sh)。
如何在本地构建并运行 EmbedIO 测试
在仓库根目录执行:
./tfb --mode verify --test embedio
tfb 脚本(tfb)会先创建 tfb Docker 网络,构建工具镜像 techempower/tfb,随后以挂载当前仓库的方式运行工具容器;工具链将自动完成 embedio 镜像的构建(embedio.dockerfile)、容器启动、端点验证与结果记录。
若想手动验证应用行为,可在构建镜像后直接运行:
docker build -f frameworks/CSharp/embedio/embedio.dockerfile -t embedio-bench frameworks/CSharp/embedio
docker run --rm -p 8080:8080 embedio-bench
curl -i http://localhost:8080/plaintext # 期望 Hello, World!
curl -i http://localhost:8080/json # 期望 {"message":"Hello, World!"}
小结
EmbedIO 测试是 TFB 中 C# 阵营一个典型的“无数据库、纯 HTTP 响应”基准用例:技术上采用 C# 13.0 / .NET 9 与 EmbedIO 3.5.2,通过声明式路由提供 /plaintext 与 /json 两个端点;实现层面以预编码字节、显式 Content-Length、关闭控制台日志等手法贴近基准测试“最小开销”的目标;工程层面通过多阶段 Alpine Dockerfile 与 benchmark_config.json / config.toml 双份元数据接入 TFB 工具链。阅读 Benchmarks/Program.cs 并结合 toolset/test_types 下的验证源码,即可完整还原该测试从请求到验证的整条链路,也为新增同类型 C# 框架测试提供了可直接对照的范本。