编写自己的插件

插件是spring-rs的核心概念之一,spring-rs正是通过插件机制扩展应用的功能

crates.io Documentation

介绍

spring是该项目的核心模块,包含了:配置管理、插件管理、组件管理。

  • 所有的插件都需要实现Plugin特征。
  • 所有的配置都需要实现Configurable特征。
  • 所有的组件都需要实现Clone特征。

注意:为了避免对Component内大结构的进行深拷贝,推荐使用newtype模式通过Arc<T>进行引用。

如何编写自己的插件

添加依赖

spring = { version = "0.1.1" }                       # 该crate中包含了插件trait的定义
serde = { workspace = true, features = ["derive"] }  # 用于解析插件的配置项
struct MyPlugin;

#[async_trait]
impl Plugin for MyPlugin {
    async fn build(&self, app: &mut AppBuilder) {
        // 调用app.get_config::<Config>(self)方法即可获取配置项
        match app.get_config::<Config>(self) {
            Ok(config) => {
                println!("{:#?}", config);
                assert_eq!(config.a, 1);
                assert_eq!(config.b, true);

                // 拿到配置项即可构建相应的组件

            }
            Err(e) => println!("{:?}", e),
        }
    }
}

/// 插件的配置
#[derive(Debug, Configurable, Deserialize)]
#[config_prefix = "my-plugin"]
struct Config {
    a: u32,
    b: bool,
}

完整代码参考plugin-example,也可以参考自带的其他插件代码。