Skip to main content

WriteBehindWriter

Struct WriteBehindWriter 

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

Write-Behind 写入器

包装一个 L2CacheBackend,将写操作同时写入缓存与内存队列, 后台任务或显式 flush() 触发批量刷新到后端存储。

§线程安全

内部使用 tokio::sync::Mutex 保护队列,可被多线程并发调用。

§示例

use sz_orm_core::l2_cache::{WriteBehindWriter, WriteOp, InMemoryBackend};
use std::sync::Arc;
use std::time::Duration;

let backend = Arc::new(InMemoryBackend::new());
let on_flush = Arc::new(|ops: Vec<WriteOp>| {
    Box::pin(async move {
        // 这里将 ops 应用到数据库(如批量 INSERT/UPDATE)
        for op in &ops {
            println!("flushing: {:?}", op);
        }
        Ok(())
    }) as std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), _>> + Send>>
    as _
});
let writer = WriteBehindWriter::new(backend.clone(), on_flush);

// 立即更新缓存,并异步刷新到数据库
writer.write(b"key1", b"value1", None).await?;

// 显式刷新所有待处理操作
writer.flush().await?;

Implementations§

Source§

impl WriteBehindWriter

Source

pub fn new(backend: Arc<dyn L2CacheBackend>, on_flush: FlushCallback) -> Self

创建 Write-Behind 写入器

§参数
  • backend:被包装的 L2 缓存后端(如 InMemoryBackendRedisBackend
  • on_flush:刷新回调,接收一批操作并应用到后端存储
Source

pub fn with_error_callback(self, on_error: ErrorCallback) -> Self

设置错误回调

flush() 失败时调用,传入失败的操作和错误信息。 注意:失败的操作会保留在队列中等待下次重试。

Source

pub async fn write( &self, key: &[u8], value: &[u8], ttl: Option<Duration>, ) -> Result<(), CacheError>

写入缓存(立即更新后端缓存 + 入队待刷新)

§参数
  • key:缓存键
  • value:缓存值(字节切片)
  • ttl:TTL,None 表示永不过期
Source

pub async fn delete(&self, key: &[u8]) -> Result<(), CacheError>

删除缓存项(立即从后端缓存删除 + 入队待刷新)

Source

pub async fn flush(&self) -> Result<(), CacheError>

刷新所有待处理操作到后端存储

将队列中的操作一次性传给 on_flush 回调。 若回调返回错误,操作保留在队列中等待下次重试。

Source

pub async fn pending_count(&self) -> usize

当前队列中待刷新的操作数(用于监控)

Source

pub fn spawn_auto_flush(self: Arc<Self>, interval: Duration) -> JoinHandle<()>

启动后台自动刷新任务

interval 触发一次 flush(),直到 WriteBehindWriter 被丢弃。 返回 JoinHandle,调用方可用于等待任务结束。

§注意

调用方需保证 WriteBehindWriter 的生命周期长于后台任务, 否则在 writer 被丢弃后,后台任务会因 Arc 引用计数归零而停止。

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> 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, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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