Lithium 框架在 TechEmpower FrameworkBenchmarks 中的 C++17 异步 Web 基准测试实现解析
Lithium 框架在 TechEmpower FrameworkBenchmarks 中的 C++17 异步 Web 基准测试实现解析
导读
本文围绕 frameworks/C++/lithium/README.md 展开,深入解析 Lithium 这一基于 epoll 与协程的现代 C++17 异步 Web 服务器框架,在 TechEmpower FrameworkBenchmarks 项目中如何实现 JSON、PLAINTEXT、DB、QUERY、CACHED QUERY、UPDATE、FORTUNES 七类基准测试。读完本文,你将掌握:Lithium 的核心 API 组织方式(HTTP 路由、SQL ORM、协程化数据库访问)、全部测试端点的 URL 映射与实现细节、两阶段 PGO 编译与 Docker 部署配置,以及数据库连接数调优和 PostgreSQL 批处理模式的原理。
Lithium 框架与基准测试背景
Lithium 是 Matthieu Garrigues(matthieu.garrigues@gmail.com)开发的现代 C++17 异步 Web 服务器框架,其技术底座是 Linux 平台的 epoll 事件循环与 协程(coroutines) 调度模型。在该基准测试仓库中,Lithium 的完整实现位于 frameworks/C++/lithium/ 目录,核心内容包含:
- 基准测试入口源码:lithium.cc
- 批处理(batch)模式入口源码:lithium_batch.cc
- 符号表定义:symbols.hh
- 构建脚本与 Dockerfile、基准测试配置(
benchmark_config.json、config.toml)
根据 README 的说明,该测试用例使用的运行库是 Lithium 框架本身的单头文件版本(lithium_http_server.hh、lithium_mysql.hh、lithium_pgsql.hh 等,构建时由 compile.sh 通过 wget 从上游仓库指定 commit 拉取)。
测试类型与对应实现文件
README 明确指出,以下所有测试类型的实现源代码均位于 lithium.cc:
| 测试类型 | 实现文件 | 对应 HTTP 端点(源码/配置) |
|---|---|---|
| JSON | lithium.cc |
GET /json |
| PLAINTEXT | lithium.cc |
GET /plaintext |
| DB | lithium.cc |
GET /db |
| QUERY | lithium.cc |
GET /queries?N= |
| CACHED QUERY | lithium.cc |
GET /cached-worlds?N= |
| UPDATE | lithium.cc |
GET /updates?N= |
| FORTUNES | lithium.cc |
GET /fortunes |
需要留意 README 与源码/配置文件之间的一处细微差异:README 的 Test URLs 一节写作 http://localhost:8080/cached-world?N= 与 http://localhost:8080/update?N=,而实际路由定义(lithium.cc 中的 my_api.get("/cached-worlds")、lithium.cc 中的 my_api.get("/updates"))以及 benchmark_config.json 中登记的 cached_query_url(/cached-worlds?N=)与 update_url(/updates?N=)均使用复数形式。实际可访问端点以源码和配置为准。
测试 URL 与路由总览
将七类测试合并起来,得到完整的本地验证 URL 清单:
- JSON:
http://localhost:8080/json - PLAINTEXT:
http://localhost:8080/plaintext - DB:
http://localhost:8080/db - QUERY:
http://localhost:8080/queries?N= - UPDATE:
http://localhost:8080/updates?N= - FORTUNES:
http://localhost:8080/fortunes - CACHED QUERY:
http://localhost:8080/cached-worlds?N=
其中 N 是查询/更新条数参数,源码通过 request.get_parameters(s::N = std::optional<std::string>()) 解析,缺省取 "1",并统一钳制在 [1, 500] 区间(N = std::max(1, std::min(N, 500)))。
源码实现深度解析
单头文件引入与编译期开关
lithium.cc 顶层通过宏开关选择数据库驱动后端:
#include "lithium_http_server.hh"
#if TFB_MYSQL
#include "lithium_mysql.hh"
#elif TFB_PGSQL
#include "lithium_pgsql.hh"
#endif
#include "symbols.hh"
using namespace li;
TFB_MYSQL/TFB_PGSQL是编译期宏,由构建脚本在编译命令中通过-DTFB_MYSQL或-DTFB_PGSQL注入,决定链接 MySQL(MariaDB)还是 PostgreSQL 驱动。symbols.hh是由 Lithium 符号生成器产出的编译期符号表,定义了s::N、s::id、s::randomNumber、s::message、s::host、s::port、s::user、s::password、s::database、s::charset、s::auto_increment、s::primary_key等符号(见 symbols.hh),它们是 Lithium 元编程(metaprogramming)ORM 与参数绑定的核心,也是using namespace li;之后s::xxx语法得以工作的前提。
主函数:启动参数、线程数与数据库连接池
int main(int argc, char* argv[]) {
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " sql_host port" << std::endl;
return 1;
}
int port = atoi(argv[2]);
int nprocs = std::thread::hardware_concurrency();
#if MONOTHREAD
int nthreads = 1;
#else
int nthreads = nprocs;
#endif
- 程序需要两个参数:数据库主机名(
sql_host)与 HTTP 监听端口(port)。 - 线程数默认取 CPU 硬件并发数(
std::thread::hardware_concurrency());若以-DMONOTHREAD编译则固定为单线程。
数据库连接配置(MySQL 分支):
auto sql_db = mysql_database(s::host = argv[1], s::database = "hello_world",
s::user = "benchmarkdbuser", s::password = "benchmarkdbpass",
s::port = 3306, s::charset = "utf8");
PostgreSQL 分支除端口(5432)与驱动函数(pgsql_database)不同外,连接参数完全一致,符合 TechEmpower 基准测试的 hello_world 库与 benchmarkdbuser/benchmarkdbpass 约定。
随后通过 sql_orm_schema 声明两张表对应的 ORM 映射:
auto fortunes = sql_orm_schema(sql_db, "Fortune").fields(
s::id(s::auto_increment, s::primary_key) = int(),
s::message = std::string());
auto random_numbers = sql_orm_schema(sql_db, "World").fields(
s::id(s::auto_increment, s::primary_key) = int(),
s::randomNumber = int());
各测试端点的实现细节
PLAINTEXT
my_api.get("/plaintext") = & {
response.set_header("Content-Type", "text/plain");
response.write("Hello, World!");
};
JSON
my_api.get("/json") = & {
response.write_json(s::message = "Hello, World!");
};
write_json 将符号映射序列化为 JSON 对象 {"message":"Hello, World!"},正好满足 toolset 中 json.py 验证器对 verify_helloworld_object 的校验要求(不区分大小写、忽略引号风格)。
DB:单条随机查询
my_api.get("/db") = & {
sql_db.max_async_connections_per_thread_ = db_nconn;
response.write_json(*random_numbers.connect(request.fiber).find_one(s::id = 1 + random_int() % 10000));
};
关键点:
random_numbers.connect(request.fiber)在请求自身的协程上下文上建立 ORM 连接,异步访问数据库期间可让出 CPU 给其他请求,这正是 Lithium 协程化异步模型的核心用法。random_int()是一个快速 LCG 伪随机实现(g_seed = 214013 * g_seed + 2531011; return (g_seed >> 16) & 0x7FFF;),用于在 1~10000 间取随机 World 行 id。
QUERY:N 条随机查询
my_api.get("/queries") = & {
sql_db.max_async_connections_per_thread_ = queries_nconn;
std::string N_str = request.get_parameters(s::N = std::optional<std::string>()).N.value_or("1");
int N = atoi(N_str.c_str());
N = std::max(1, std::min(N, 500));
auto c = random_numbers.connect(request.fiber);
response.write_json_generator(N, [&] { return *c.find_one(s::id = 1 + random_int() % 10000); });
};
write_json_generator(N, lambda) 以惰性生成器方式逐条写出 JSON 数组元素,避免一次性构造完整向量;toolset 中 query.py 验证器会依次用 2、0、foo、501、空串等用例验证数组长度与字段类型。
CACHED QUERY:全表缓存 + N 条随机读取
先启动时一次性把整张 World 表加载进内存缓存:
cache<decltype(mmm(s::id = int(), s::randomNumber = int()))> world_cache;
random_numbers.connect().forall([&] (const auto& number) {
world_cache.insert(metamap_clone(number));
});
路由处理则只从 world_cache 的 std::vector 缓冲中按下标随机取数,完全不打数据库:
my_api.get("/cached-worlds") = & {
std::string N_str = request.get_parameters(s::N = std::optional<std::string>()).N.value_or("1");
int N = atoi(N_str.c_str());
response.write_json_generator(std::max(1, std::min(N, 500)),
[&] { return world_cache.get(1 + random_int() % 10000); });
};
UPDATE:读取 N 行、改写、批量更新
UPDATE 是七类测试中逻辑最复杂的一条:
my_api.get("/updates") = & {
sql_db.max_async_connections_per_thread_ = updates_nconn;
std::string N_str = request.get_parameters(s::N = std::optional<std::string>()).N.value_or("1");
int N = atoi(N_str.c_str());
N = std::max(1, std::min(N, 500));
std::vector<decltype(random_numbers.all_fields())> numbers(N);
{
auto c = random_numbers.connect(request.fiber);
auto& raw_c = c.backend_connection();
#if TFB_MYSQL
raw_c("START TRANSACTION");
#endif
for (int i = 0; i < N; i++) {
numbers[i] = *c.find_one(s::id = 1 + random_int() % 10000);
numbers[i].randomNumber = 1 + random_int() % 10000;
}
std::sort(numbers.begin(), numbers.end(), [] (auto a, auto b) { return a.id < b.id; });
c.bulk_update(numbers);
#if TFB_MYSQL
raw_c("COMMIT");
#endif
}
response.write_json(numbers);
};
实现要点:
- 在同一连接上先
N次随机读取并改写randomNumber,再按id排序后bulk_update批量更新(排序是为了避免死锁,符合基准测试规范)。 - MySQL 分支通过
backend_connection()取原生连接显式执行START TRANSACTION/COMMIT包裹批量更新;PostgreSQL 分支无需此操作。
FORTUNES:HTML 渲染与 XSS 转义
my_api.get("/fortunes") = & {
sql_db.max_async_connections_per_thread_ = fortunes_nconn;
typedef decltype(fortunes.all_fields()) fortune;
std::vector<fortune> table;
{
auto c = fortunes.connect(request.fiber);
c.forall([&] (const auto& f) { table.emplace_back(metamap_clone(f)); });
}
table.emplace_back(0, "Additional fortune added at request time.");
std::sort(table.begin(), table.end(),
[] (const fortune& a, const fortune& b) { return a.message < b.message; });
li::growing_output_buffer ss;
ss << "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>";
for(auto& f : table) {
ss << "<tr><td>" << f.id << "</td><td>";
escape_html_entities(ss, f.message);
ss << "</td></tr>";
}
ss << "</table></body></html>";
response.set_header("Content-Type", "text/html; charset=utf-8");
response.write(ss.to_string_view());
};
实现要点:
- 全表
forall读取后追加内置行"Additional fortune added at request time."(id 为 0),再按message字典序排序,这是 FORTUNES 测试的标准步骤。 - 模板顶部自定义的
escape_html_entities函数把&、"、'、<、>分别转义为&、"、'、<、>,配合growing_output_buffer增量缓冲拼接 HTML;toolset 中 fortune.py 使用FortuneHTMLParser逐行比对 id/message 校验输出。
数据库连接数调优
源码通过编译期宏 N_SQL_CONNECTIONS 统一控制各端点的每线程异步连接数;未定义该宏时使用按数据库/端点区分的默认值:
| 端点 | MySQL(TFB_MYSQL)默认连接数 | PostgreSQL(TFB_PGSQL)默认连接数 |
|---|---|---|
DB(db_nconn) |
5 | 5 |
QUERY(queries_nconn) |
4 | 3 |
FORTUNES(fortunes_nconn) |
5 | 7 |
UPDATE(updates_nconn) |
2 | 3 |
定义 -DN_SQL_CONNECTIONS=N 时四个端点统一取 N。在批处理变体 lithium_batch.cc 中,连接数直接通过 pgsql_database(..., s::max_async_connections_per_thread = N_SQL_CONNECTIONS) 在创建数据库对象时注入,并在启动时打印 "Using N sql connections x threads threads."。
编译流程:两阶段 PGO 与批处理变体
标准编译脚本 compile.sh
compile.sh 接收两个参数:DB_FLAG(TFB_MYSQL 或 TFB_PGSQL)与可选的 Lithium 上游 commit(默认 a046b3345098157849d9e2ab49a475aaabf4a90f):
DB_FLAG=$1
COMMIT="$2"
if [ "$COMMIT" = "" ]; then
COMMIT="a046b3345098157849d9e2ab49a475aaabf4a90f"
fi
if [ $DB_FLAG = "TFB_MYSQL" ]; then
CXX_FLAGS="-I /usr/include/mariadb -lmariadbclient "
wget .../lithium/$COMMIT/single_headers/lithium_mysql.hh
elif [ $DB_FLAG = "TFB_PGSQL" ]; then
CXX_FLAGS="-lpthread -L/usr/lib -lpq -I/postgres-bab150.../src/include"
wget .../lithium/$COMMIT/single_headers/lithium_pgsql.hh
fi
wget .../lithium/$COMMIT/single_headers/lithium_http_server.hh
编译命令采用 PGO(Profile-Guided Optimization)两阶段策略,先用 clang++ -fprofile-instr-generate=./profile.prof -flto ... -DPROFILE_MODE -O3 -march=native -std=c++17 编译出插桩版本:
-DPROFILE_MODE会启用源码中的siege()预热函数(lithium.cc),它建立 512 个并发连接,以 2 并发 × 1000 次对/json、/plaintext、/db、/queries?N=20、/fortunes、/updates?N=20、/cached-world?N=100发请求;- 插桩版以
tfb-database为数据库主机、8081端口短暂运行后,用llvm-profdata-10 merge -output=./profile.pgo ./profile.prof归并 profile; - 第二遍以
-fprofile-instr-use=./profile.pgo -flto ... -O3 -march=native重新编译产出最终二进制/lithium_tbf; - 最终以
./lithium_tbf tfb-database 8080正式启动,监听 8080 端口。 - 脚本也保留了
g++ -flto ...的 GCC 编译分支作为非 PGO 备选。
PostgreSQL 专用:编译 libpq
由于需要定制 libpq(批处理补丁场景),compile_libpq.sh 会下载指定 commit 的 PostgreSQL 源码,./configure --prefix=/usr CFLAGS='-O3 -march=native -flto' 后仅编译安装 src/interfaces/libpq,并把 postgres_ext.h、pg_config_ext.h 拷入 /usr/include。
批处理(Batch)变体
compile-batch.sh 编译 lithium_batch.cc,对应 postgres-batch 测试:
- 目前仅支持 PostgreSQL,若传入
TFB_MYSQL会直接输出"ERROR: Only Postgres has pipelining support for now."并退出; - 默认 commit 为
10b72ad8ce16528ff642f802e266a975964d06f9,额外拉取lithium_http_backend.hh; - 编译时固定
-DN_SQL_CONNECTIONS=1(单连接下的 libpq batch/pipelining 模式); - 批处理模式的核心差异在 QUERY 与 UPDATE 实现:QUERY 先在一个协程内发完 N 条
find_one请求(非阻塞发起),再逐个results[i]()取回结果;UPDATE 通过c.bulk_update(numbers)后调用c.backend_connection().end_of_batch()与req.flush_results()触发批量流水线刷新。该实现依赖 compile_libpq.sh 中batchmode_patch参数打上的 libpq 批处理补丁(v22-0001-libpq-batch.patch)。
Docker 部署:五个镜像变体
仓库为五种测试组合各提供一份 Dockerfile,基础镜像均为 buildpack-deps:focal,统一 EXPOSE 8080:
| Dockerfile | 数据库 | 构建命令 | 说明 |
|---|---|---|---|
| lithium.dockerfile | MySQL | CMD ./compile.sh TFB_MYSQL |
安装 clang、libboost-context-dev、libboost-dev、libmariadb-dev |
| lithium-postgres.dockerfile | PostgreSQL | CMD ./compile.sh TFB_PGSQL |
先 RUN ./compile_libpq.sh 编译 libpq,ENV LD_LIBRARY_PATH=/usr/lib |
| lithium-postgres-beta.dockerfile | PostgreSQL | CMD ./compile.sh TFB_PGSQL a046b33... |
锁定指定上游 commit 的 beta 变体 |
| lithium-postgres-batch.dockerfile | PostgreSQL | RUN ./compile_libpq.sh batchmode_patch + CMD ./compile-batch.sh TFB_PGSQL |
打 libpq 批处理补丁后编译批处理模式 |
| lithium-postgres-batch-beta.dockerfile | PostgreSQL | CMD ./compile-batch.sh TFB_PGSQL 78ccb29... |
批处理模式的 beta 变体 |
PostgreSQL 类镜像额外安装 bison、flex(编译 libpq 所需)。所有变体统一使用 COPY ./ ./ 把仓库目录拷入容器,因此源码、symbols.hh 与各构建脚本会被直接使用。
基准测试配置声明
benchmark_config.json
benchmark_config.json 登记了三种测试组合,端口统一为 8080:
- default(Lithium-mysql):
database: "mysql",URL 依次为/json、/db、/queries?N=、/fortunes、/updates?N=、/plaintext、/cached-worlds?N=; - postgres(Lithium-postgres):
database: "Postgres",URL 与 default 一致; - postgres-beta(Lithium-postgres-beta):同 Postgres 配置,用于锁定 beta commit 的对照测试。
三条配置共同的元数据为:approach: "Realistic"、classification: "Micro"、language: "C++"、orm: "Full"、webserver: "None"、os: "Linux"、database_os: "Linux",即框架自带完整 ORM 且不依赖外部 Web 服务器,直接监听 8080 端口。
config.toml
config.toml 是 tfb 工具链的新版配置,声明 framework.name = "lithium"、作者邮箱,并定义了四个测试组合:[main](MySQL)、[postgres-beta]、[postgres]、[postgres-batch]。其中 [postgres-batch] 与 [postgres-batch-beta] 只登记 db、query、update、fortune 四个 URL(不含 plaintext/json/cached_query),与批处理编译脚本的取舍一致。
如何本地验证与复现
- 容器内构建:按上表选择对应 Dockerfile,例如 MySQL 变体
docker build -f frameworks/C++/lithium/lithium.dockerfile .,构建后容器CMD会自动执行compile.sh TFB_MYSQL完成编译并以tfb-database 8080启动服务。 - 手动编译:在已安装
clang、libboost-context-dev、wget(MySQL 还需libmariadb-dev)的环境下,直接运行./compile.sh TFB_MYSQL或./compile.sh TFB_PGSQL;PostgreSQL 变体需先执行./compile_libpq.sh。 - 启动后验证:监听端口固定为 8080,直接请求上文 Test URL 清单中的端点即可。也可以借助 tfb 工具链的验证器确认响应合规——各测试类型的校验逻辑见 toolset/test_types/ 下的
json.py、query.py、cached-query.py、fortune.py等(例如 JSON 必须返回{"message":"Hello, World!"}对象,QUERY 返回的数组长度与N一致且元素含id、randomNumber整数字段)。 - 性能剖析(PGO):
compile.sh的插桩阶段会自动完成“预热 → 采集 profile → 重编译”闭环,无需手工干预;若只想快速验证功能而非测性能,可直接用脚本中保留的 GCC 分支或去掉-DPROFILE_MODE编译。
小结
Lithium 在 TechEmpower FrameworkBenchmarks 中的实现,充分展示了其三个核心设计主张:C++17 元编程驱动的 HTTP API 与 SQL ORM、基于 epoll + 协程的异步调度(请求可在数据库等待时让出 CPU)、以及面向极致性能的编译期调优(march=native、LTO、PGO、按端点独立控制连接池)。七类测试端点全部由 lithium.cc 一个源文件承载,配合 symbols.hh 的符号系统即可完成从路由到 ORM 再到 JSON/HTML 响应的完整闭环;PostgreSQL 批处理变体则进一步验证了 libpq pipelining 在协程模型中的可行性。对于希望在异步 C++ Web 服务中落地“单文件多端点 + 协程化数据库访问 + PGO 构建”方案的开发者,这份基准测试实现是一份可直接借鉴的完整样本。