是否有可能以某种方式构建和缓存整个 MySQL 并
例如,将依赖项火箭发射到两个更大的库中,并避免这样做
每次都有效吗?
我们可以将静态编译的 MySQL/Rocket 库链接到我们的 Rust 项目中(通过 C++ 包装器)。我们来试试吧。
- Create
build.rs
文件中,我们将使用 cxx crate 将 MySQL 和 Rocket 依赖项编译到静态库中。
extern crate cxx_build;
fn main() {
cxx_build::bridge("src/wrapper.rs")
.file("src/mysql_wrapper.cpp")
.file("src/rocket_wrapper.cpp")
.flag("-std=c++17")
.compile("mysql_wrapper", "rocket_wrapper");
}
- 创建名为的包装文件
wrapper.rs
, mysql_wrapper.cpp
and rocket_wrapper.cpp
在我们的 src 目录中。
// mysql_wrapper.cpp
#include <mysql.h>
void init_mysql() {
mysql_library_init(0, NULL, NULL);
}
void cleanup_mysql() {
mysql_library_end();
}
// rocket_wrapper.cpp
#include <rocket.h>
#include <iostream>
extern "C" {
void init_rocket() {
std::vector<std::string> args = { "myapp", "--port=8000" };
rocket::config::Config config;
config.from_args(args);
rocket::ignite(config);
}
void stop_rocket() {
rocket::shutdown();
}
}
// wrapper.rs
#[cxx::bridge]
mod ffi {
unsafe extern "C++" {
fn init_mysql();
fn cleanup_mysql();
fn init_rocket();
fn stop_rocket();
}
}
- 修改 Rust 代码(
main.rs
)来链接静态库,而不是直接链接 MySQL 和 Rocket 依赖项。
// main.rs
mod ffi {
#[cxx::bridge]
mod ffi {
unsafe extern "C++" {
fn init_mysql();
fn cleanup_mysql();
fn init_rocket();
fn stop_rocket();
}
}
}
fn main() {
unsafe {
ffi::init_mysql();
}
// Usage of MySQL lib here
unsafe {
ffi::cleanup_mysql();
}
unsafe {
ffi::init_rocket();
}
// Usage of Rocket f/work here
unsafe {
ffi::stop_rocket();
}
}
- 构建项目
cargo build
就是这个。这将包括 mysql 和 Rocket 作为静态库,并且不会从Cargo.toml
作为直接依赖。我不确定我们是否会获得真正显着的收益,它可能取决于项目结构,并且只有在您不打算更新这些依赖项的版本时才应该使用。我可能需要进行性能检查,但稍后。