#service #tokio #macro #async #framework #message #interlink

interlink-derive

为Interlink提供衍生宏

3个版本

0.1.2 2023年4月28日
0.1.1 2023年4月2日
0.1.0 2023年2月20日

#584 in #message


2个crate中使用(通过interlink

MIT许可证

7KB

Interlink

License Cargo Version Cargo Downloads

Interlink异步框架

InterlinkTokio异步运行时上运行,并使用"服务"来构建应用的一部分,可以通过"链接"与这些服务通信,允许向服务发送消息,然后由服务处理

🚩 此项目处于非常初级的阶段,因此预计会有破坏性的变化,在此阶段,其功能尚未完全实现或测试

将以下Cargo依赖项添加到项目中以包含Interlink

[dependencies]
interlink = "0.1" 

启动服务

为了获取服务的链接并使服务运行,您首先需要启动该服务

use interlink::prelude::*;

/// Define your backing structure for the service you can use
/// the service derive macro here or implement the trait to
/// get access to the `started` and `stopping` hooks
#[derive(Service)]
struct Example;

// You must be within the tokio runtime to use interlink
#[tokio::main]
async fn main() {
    // Create the service
    let service = Example {};
    // Start the service to get a link to the service
    let link = service.start();
}

向服务发送消息

要与服务和之间通信,您使用消息。以下是如何创建和发送消息的示例。

use interlink::prelude::*;

// Define your backing structure for the service
#[derive(Service)]
struct Example;

// The message struct with a string response type
#[derive(Message)]
#[msg(rtype = "String")]
struct TextMessage {
    value: String,
}

/// Implement a handler for the message type
impl Handler<TextMessage> for Example {

    /// Basic response type which just responds with the value
    type Response = Mr<TextMessage>

    fn handle(
        &mut self, 
        msg: TextMessage, 
        ctx: &mut ServiceContext<Self>
    ) -> Self::Response {
        println!("Got message: {}", &msg.value);
        Mr(msg.value)
    }
}

// You must be within the tokio runtime to use interlink
#[tokio::main]
async fn main() {
    // Create the service
    let service = Example {};
    // Start the service to get a link to the service
    let link = service.start();

    // Send the text message to the service and await the response
    let res: String = link.send(TextMessage {
            value: "Example".to_string(),
        })
        .await
        .unwrap();

    assert_eq!(&res, "Example");

    // You can also send without waiting for a response
    link.do_send(TextMessage {
            value: "Example".to_string(),
        })
        .unwrap();

}

依赖关系

~0.6–1.1MB
~25K SLoC