pub struct BatchLoader<K, V>{ /* private fields */ }Expand description
批量加载器
将 N 个单条加载请求合并为 ⌈N/batch_size⌉ 次批量加载,避免 N+1 查询问题。
§泛型参数
K:主键类型(必须实现Hash + Eq + Clone)V:值类型
§示例
use sz_orm_query::entity_graph::BatchLoader;
use std::collections::HashMap;
fn load_users(ids: &[i64]) -> HashMap<i64, String> {
ids.iter().map(|id| (*id, format!("user_{}", id))).collect()
}
let loader = BatchLoader::new(100, Box::new(load_users));
let users = loader.load_many(&[1, 2, 3]);
assert_eq!(users.len(), 3);Implementations§
Source§impl<K, V> BatchLoader<K, V>
impl<K, V> BatchLoader<K, V>
Sourcepub fn new(
batch_size: usize,
loader: Box<dyn Fn(&[K]) -> HashMap<K, V> + Sync + Send>,
) -> BatchLoader<K, V>
pub fn new( batch_size: usize, loader: Box<dyn Fn(&[K]) -> HashMap<K, V> + Sync + Send>, ) -> BatchLoader<K, V>
Sourcepub fn load_many(&self, keys: &[K]) -> HashMap<K, V>
pub fn load_many(&self, keys: &[K]) -> HashMap<K, V>
批量加载多个 key
- 自动跳过缓存中已有的 key
- 按 batch_size 分批调用 loader
- 返回所有 key 对应的 value(包含缓存与新加载的)
Sourcepub fn clear_cache(&self)
pub fn clear_cache(&self)
清空缓存
Sourcepub fn cache_size(&self) -> usize
pub fn cache_size(&self) -> usize
返回当前缓存大小
Sourcepub fn batch_size(&self) -> usize
pub fn batch_size(&self) -> usize
返回 batch_size
Auto Trait Implementations§
impl<K, V> !Freeze for BatchLoader<K, V>
impl<K, V> !RefUnwindSafe for BatchLoader<K, V>
impl<K, V> !UnwindSafe for BatchLoader<K, V>
impl<K, V> Send for BatchLoader<K, V>
impl<K, V> Sync for BatchLoader<K, V>
impl<K, V> Unpin for BatchLoader<K, V>
impl<K, V> UnsafeUnpin for BatchLoader<K, V>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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