Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

自定义组件封装

封装中间件组件

将中间件 + 配置 + 注册封装为 Builder 扩展:

#![allow(unused)]
fn main() {
use webx::*;

pub trait TenantBuilderExt {
    fn use_multi_tenant(self, config: TenantConfig) -> Self;
}

impl TenantBuilderExt for HostBuilder {
    fn use_multi_tenant(self, config: TenantConfig) -> Self {
        let resolver = Arc::new(TenantResolver::new(config));
        let for_di = Arc::clone(&resolver);
        let for_mw = Arc::clone(&resolver);

        self
            // 普通组件仍走 DI 注册
            .register(move |svc| svc.singleton::<TenantResolver>(move |_| Arc::clone(&for_di)))
            // 中间件必须通过 HostBuilder 扩展方法注册(不能在 register 闭包内直接添加)
            .use_middleware(MiddlewareSpec::factory(move || {
                Arc::new(TenantMiddleware::new(Arc::clone(&for_mw))) as Arc<dyn IMiddleware>
            }))
    }
}
}

消费方:

#![allow(unused)]
fn main() {
Host::builder().use_multi_tenant(config).build()
}

MiddlewareSpec::new::<T>() 注册 Default 中间件;需要构造参数时用 MiddlewareSpec::factory(..)。

封装服务组件

#![allow(unused)]
fn main() {
// 在你的 library crate 中
pub struct EmailModule;

impl EmailModule {
    pub fn register(svc: ServiceCollection, config: SmtpConfig) -> ServiceCollection {
        svc.singleton::<EmailService>(move |_| Arc::new(EmailService::new(config.clone())))
    }
}

// main.rs
.register(|svc| EmailModule::register(svc, smtp_config))
}

封装 Handler 基类模式

Rust 无继承,用组合替代:

#![allow(unused)]
fn main() {
pub struct BaseHandler {
    pub cache: Arc<dyn IDistributedCache>,
    pub mediator: Arc<Mediator>,
}

impl BaseHandler {
    pub async fn get_cached_user(&self, id: &str) -> Result<UserDto> {
        self.cache.get_or_create(&format!("user:{}", id), async {
            self.mediator.send(GetUserRequest { id: id.into() }).await
        }).await
    }
}

pub struct GetUserProfileHandler {
    base: BaseHandler,
}
}

发布为独立 Crate

通用组件可发布为独立 crate,只依赖 rust-webx-core:

[dependencies]
rust-webx-core = "0.5"

小结

好的封装让消费方一行启用,内部隐藏注册细节和配置逻辑。

下一节:自定义 Endpoint