Skip to main content

ServiceRuntime

Struct ServiceRuntime 

Source
pub struct ServiceRuntime { /* private fields */ }
Expand description

服务运行时

统一管理服务的生命周期,包括:

  • 任务启动和管理(HTTP, gRPC, MQ 消费者等)
  • 服务注册和注销
  • 优雅停机
  • 状态监控

§示例

§简单模式(不注册服务)

use flare_core_runtime::ServiceRuntime;
use flare_core_runtime::task::SpawnTask;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let runtime = ServiceRuntime::new("my-service")
        .add_spawn("my-task", async { Ok(()) });

    runtime.run().await?;
    Ok(())
}

§完整模式(带服务注册)

use flare_core_runtime::ServiceRuntime;
use std::net::SocketAddr;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let runtime = ServiceRuntime::new("my-service")
        .with_address("0.0.0.0:8080".parse().unwrap())
        .add_spawn("grpc", async { Ok(()) });

    runtime.run_with_registration(|addr| {
        Box::pin(async move {
            // 注册服务
            Ok(None)
        })
    }).await?;
    Ok(())
}

Implementations§

Source§

impl ServiceRuntime

Source

pub fn new(service_name: impl Into<String>) -> Self

创建新的服务运行时

§参数
  • service_name - 服务名称(用于日志和服务注册)
§示例
use flare_core_runtime::ServiceRuntime;

let runtime = ServiceRuntime::new("my-service");
Source

pub fn simple() -> Self

创建简单的任务运行器(无需服务名和地址)

用于运行 MQ 消费者、自定义任务等简单场景

§示例
use flare_core_runtime::ServiceRuntime;

// 仅运行 MQ 消费者
let runtime = ServiceRuntime::simple()
    .add_spawn("kafka-consumer", async { Ok(()) });
Source

pub fn mq_consumer() -> Self

创建 MQ 消费者运行器

专门用于运行 MQ 消费者的便捷方法

§示例
use flare_core_runtime::ServiceRuntime;

let runtime = ServiceRuntime::mq_consumer()
    .add_spawn("kafka-consumer", async { Ok(()) })
    .add_spawn("nats-consumer", async { Ok(()) });
Source

pub fn tasks() -> Self

创建自定义任务运行器

专门用于运行自定义任务的便捷方法

§示例
use flare_core_runtime::ServiceRuntime;

let runtime = ServiceRuntime::tasks()
    .add_spawn("task-1", async { Ok(()) })
    .add_spawn("task-2", async { Ok(()) });
Source

pub fn with_address(self, address: SocketAddr) -> Self

设置服务地址

§参数
  • address - 服务地址(用于服务注册)
Source

pub fn with_config(self, config: RuntimeConfig) -> Self

设置运行时配置

Source

pub fn with_registry(self, registry: Box<dyn ServiceRegistry>) -> Self

设置服务注册器

Source

pub fn with_health_checker(self, checker: HealthChecker) -> Self

设置健康检查器

Source

pub fn add_health_check(self, check: Arc<dyn HealthCheck>) -> Self

添加健康检查项

Source

pub fn with_health_failure_action(self, action: HealthFailureAction) -> Self

设置健康检查失败时的行为

Source

pub fn add_task(self, task: Box<dyn Task>) -> Self

添加任务

§参数
  • task - 要添加的任务(实现了 Task trait)
Source

pub fn add_spawn<Fut>(self, name: impl Into<String>, future: Fut) -> Self
where Fut: Future<Output = Result<(), Box<dyn Error + Send + Sync>>> + Send + 'static,

添加 spawn 任务(直接添加 Future)

§参数
  • name - 任务名称
  • future - 要运行的 Future
§示例
use flare_core_runtime::ServiceRuntime;

let runtime = ServiceRuntime::new("my-service")
    .add_spawn("my-task", async { Ok(()) });
Source

pub fn add_spawn_with_deps<Fut>( self, name: impl Into<String>, future: Fut, dependencies: Vec<String>, ) -> Self
where Fut: Future<Output = Result<(), Box<dyn Error + Send + Sync>>> + Send + 'static,

添加 spawn 任务(带依赖)

Source

pub fn add_spawn_with_shutdown<F, Fut>( self, name: impl Into<String>, future_fn: F, ) -> Self
where F: FnOnce(Receiver<()>) -> Fut + Send + 'static, Fut: Future<Output = Result<(), Box<dyn Error + Send + Sync>>> + Send + 'static,

添加 spawn 任务(需要 shutdown)

Source

pub fn state_tracker(&self) -> Arc<StateTracker> ⓘ

获取状态追踪器

Source

pub async fn run(self) -> Result<()>

运行服务(简单模式,不注册服务)

执行以下步骤:

  1. 启动所有任务
  2. 等待所有任务就绪
  3. 等待关闭信号(Ctrl+C)
  4. 优雅关闭所有任务
Source

pub async fn run_with_signals( self, signals: Vec<Box<dyn ShutdownSignal>>, ) -> Result<()>

运行服务(带自定义信号)

§参数
  • signals - 自定义停机信号列表
Source

pub async fn run_with_registration<F, Fut>(self, register_fn: F) -> Result<()>
where F: FnOnce(SocketAddr) -> Fut, Fut: Future<Output = Result<Option<Box<dyn ServiceRegistry>>, Box<dyn Error + Send + Sync>>> + Send,

运行服务(带服务注册)

执行以下步骤:

  1. 启动所有任务
  2. 等待所有任务就绪
  3. 注册服务
  4. 等待关闭信号
  5. 注销服务
  6. 优雅关闭所有任务
Source

pub async fn run_with_registration_and_signals<F, Fut>( self, register_fn: F, signals: Vec<Box<dyn ShutdownSignal>>, ) -> Result<()>
where F: FnOnce(SocketAddr) -> Fut, Fut: Future<Output = Result<Option<Box<dyn ServiceRegistry>>, Box<dyn Error + Send + Sync>>> + Send,

运行服务(带服务注册 + 自定义停机信号)

聚合部署进程可注入 ChannelSignal, 让多个注册型服务共享同一个外部生命周期控制。

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more