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>) -> ServiceRuntime

创建新的服务运行时

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

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

pub fn simple() -> ServiceRuntime

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

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

§示例
use flare_core_runtime::ServiceRuntime;

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

pub fn mq_consumer() -> ServiceRuntime

创建 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() -> ServiceRuntime

创建自定义任务运行器

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

§示例
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) -> ServiceRuntime

设置服务地址

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

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

设置运行时配置

Source

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

设置服务注册器

Source

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

设置健康检查器

Source

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

添加健康检查项

Source

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

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

Source

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

添加任务

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

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

添加 spawn 任务(带依赖)

Source

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

添加 spawn 任务(需要 shutdown)

Source

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

获取状态追踪器

Source

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

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

执行以下步骤:

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

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

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

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

pub async fn run_with_registration<F, Fut>( self, register_fn: F, ) -> Result<(), Error>
where F: FnOnce(SocketAddr) -> Fut, Fut: Future<Output = Result<Option<Box<dyn ServiceRegistry>>, Box<dyn Error + Sync + Send>>> + 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<(), Error>
where F: FnOnce(SocketAddr) -> Fut, Fut: Future<Output = Result<Option<Box<dyn ServiceRegistry>>, Box<dyn Error + Sync + Send>>> + 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> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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