Struct MemoryCache

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

High-performance in-memory cache implementation.

MemoryCache provides fast, local caching with automatic expiration support. It’s ideal for single-instance applications or when you need very low latency cache access. The cache is thread-safe and supports concurrent reads and writes.

§Features

  • Thread-safe: Safe for concurrent access from multiple threads
  • TTL Support: Automatic expiration of cache entries
  • Memory efficient: Expired entries are cleaned up automatically
  • Fast access: O(1) average case for get/set operations
  • Flexible TTL: Per-entry TTL or default TTL for all entries

§Examples

§Basic Usage

use torch_web::cache::MemoryCache;
use std::time::Duration;

let cache = MemoryCache::new(Some(Duration::from_secs(300))); // 5 minute default TTL

// Set a value with default TTL
cache.set("user:123", "John Doe", None).await;

// Set a value with custom TTL
cache.set("session:abc", "active", Some(Duration::from_secs(3600))).await;

// Get a value
if let Some(name) = cache.get("user:123").await {
    println!("User name: {}", name);
}

§With JSON Serialization

use torch_web::cache::MemoryCache;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct User {
    id: u32,
    name: String,
    email: String,
}

let cache = MemoryCache::new(None); // No default TTL

let user = User {
    id: 123,
    name: "John Doe".to_string(),
    email: "john@example.com".to_string(),
};

// Serialize and cache
let user_json = serde_json::to_string(&user)?;
cache.set("user:123", &user_json, Some(Duration::from_secs(3600))).await;

// Retrieve and deserialize
if let Some(cached_json) = cache.get("user:123").await {
    let cached_user: User = serde_json::from_str(&cached_json)?;
    println!("Cached user: {}", cached_user.name);
}

§Cache Invalidation

use torch_web::cache::MemoryCache;

let cache = MemoryCache::new(None);

// Set some values
cache.set("key1", "value1", None).await;
cache.set("key2", "value2", None).await;

// Remove a specific key
cache.delete("key1").await;

// Clear all entries
cache.clear().await;

Implementations§

Source§

impl MemoryCache

Source

pub fn new(default_ttl: Option<Duration>) -> Self

Source

pub async fn get(&self, key: &str) -> Option<String>

Source

pub async fn set( &self, key: &str, value: &str, ttl: Option<Duration>, ) -> Result<(), Box<dyn Error>>

Source

pub async fn delete(&self, key: &str) -> Result<bool, Box<dyn Error>>

Source

pub async fn clear(&self) -> Result<(), Box<dyn Error>>

Source

pub async fn cleanup_expired(&self) -> Result<usize, Box<dyn Error>>

Source

pub async fn size(&self) -> usize

Trait Implementations§

Source§

impl Cache for MemoryCache

Source§

fn get( &self, key: &str, ) -> Pin<Box<dyn Future<Output = Option<String>> + Send + '_>>

Source§

fn set( &self, key: &str, value: &str, ttl: Option<Duration>, ) -> Pin<Box<dyn Future<Output = Result<(), Box<dyn Error>>> + Send + '_>>

Source§

fn delete( &self, key: &str, ) -> Pin<Box<dyn Future<Output = Result<bool, Box<dyn Error>>> + Send + '_>>

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 = 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