Skip to main content

RedisCacheStore

Struct RedisCacheStore 

Source
pub struct RedisCacheStore<Conn = ConnectionManager>
where Conn: RedisConnection,
{ /* private fields */ }
Available on crate feature redis only.
Expand description

A store on a Redis-family server. One store holds values of every type as JSON; get::<User> and set(&key, user, None) name the type per call. Reads decode the JSON into the type you name, and nothing in Redis records a Rust type, so other languages can share the keys.

Connect it to a single server with a ConnectionManager, to a Redis Cluster with a ClusterConnection, or behind Sentinel with a SentinelConnection. On a cluster, remove_prefix and clear scan every primary.

Implementations§

Source§

impl<Conn> RedisCacheStore<Conn>
where Conn: RedisConnection,

Source

pub fn new(name: &str, conn: Conn) -> Result<RedisCacheStore<Conn>, CacheError>

A store named name, such as app or tenant:eu, on conn. Fails with CacheError::InvalidKey when the name is empty or has an empty level. A ConnectionManager reconnects after a lost connection.

On a Redis Cluster, give it a cluster connection. The client finds the other nodes from the one it is given:

use sisa_caching_redis::{RedisCacheStore, redis::cluster::ClusterClient};

let client = ClusterClient::new(vec!["redis://10.0.0.1:6379"])?;
let cache = RedisCacheStore::new("app", client.get_async_connection().await?)?;
Source

pub fn with_settings( self, settings: RedisCacheSettings, ) -> Result<RedisCacheStore<Conn>, CacheError>

Replaces the store’s settings. Fails when one is out of range, such as a TTL over 365 days, so a bad value stops setup instead of a later write.

Source

pub fn settings(&self) -> &RedisCacheSettings

The settings the store runs with.

Source§

impl RedisCacheStore

Source

pub async fn connect( name: &str, info: impl IntoConnectionInfo, ) -> Result<RedisCacheStore, RedisCacheError>

Connects to one server, such as redis://127.0.0.1:6379, or rediss:// for TLS with the tls-rustls or tls-native-tls feature. info is a URL or a redis::ConnectionInfo. The connection is built with connection_config: while the server is down a call fails at once, and the next one connects again. For other timeouts, or for a cluster or Sentinel, build the connection and use new.

Source

pub async fn from_client( name: &str, client: Client, ) -> Result<RedisCacheStore, RedisCacheError>

Like connect, on a client built by hand, such as one that trusts a private CA or shows a client certificate:

use sisa_caching_redis::{
    RedisCacheStore,
    redis::{Client, ClientTlsConfig, TlsCertificates},
};

let client = Client::build_with_tls(
    "rediss://cache.internal:6380",
    TlsCertificates {
        client_tls: Some(ClientTlsConfig {
            client_cert: std::fs::read("client.crt")?,
            client_key: std::fs::read("client.key")?,
        }),
        root_cert: Some(std::fs::read("ca.crt")?),
    },
)?;
let cache = RedisCacheStore::from_client("app", client).await?;

Trait Implementations§

Source§

impl<Conn> CacheStore for RedisCacheStore<Conn>
where Conn: RedisConnection,

Source§

type Error = RedisCacheError

What the store’s calls fail with. Every CacheError converts into it.
Source§

fn name(&self) -> &KeyPrefix

The store’s name, written in front of every key it stores.
Source§

fn cache_settings(&self) -> &CacheSettings

The store’s TTL, refresh-ahead and lock settings. A hybrid store returns its own, which both of its layers follow.
Source§

async fn get_entry<CV>( &self, key: &str, ) -> Result<Option<CacheEntry<CV>>, RedisCacheError>
where CV: CacheValue,

The entry under key as a CV, or None when it is missing or expired. The memory store fails with CacheError::TypeMismatch when it holds another Rust type there. The Redis store decodes its JSON into CV, so another type whose fields fit reads it too, and JSON that doesn’t fit is an error. The entry is as it was when looked up: it can expire while a slow Clone of its value, or its decoding, runs.
Source§

async fn set_entry<CV>( &self, key: &str, entry: CacheEntry<CV>, ) -> Result<(), RedisCacheError>
where CV: CacheValue,

Stores entry as it is: its creation time and TTL are kept, and it expires when the entry does, not after this store’s default TTL. A store may hold it for less, as a hybrid store’s local layer does for local.ttl_secs. get_entry from one store and set_entry into another copies an entry without changing it.
Source§

async fn remove(&self, key: &str) -> Result<bool, RedisCacheError>

Removes key, and returns whether it was there.
Source§

async fn remove_prefix(&self, prefix: &str) -> Result<usize, RedisCacheError>

Removes every key under prefix, matched by whole levels (user removes user:42, not users:42, nor the key user itself), and returns how many. Fails with CacheError::InvalidKey when prefix is empty or has an empty level. Read more
Source§

async fn clear(&self) -> Result<(), RedisCacheError>

Removes every key in this store, and nothing outside it.
Source§

fn get<CV>( &self, key: &str, ) -> impl Future<Output = Result<Option<CV>, Self::Error>> + Send
where CV: CacheValue,

The value under key as a CV, or None when it is missing or expired.
Source§

fn set<CV>( &self, key: &str, value: CV, options: impl Into<Option<CacheOptions>> + Send, ) -> impl Future<Output = Result<(), Self::Error>> + Send
where CV: CacheValue,

Stores value under key, replacing what is there. options sets this write’s TTL; None uses the store’s default TTL. Fails when the TTL is over 365 days. Read more
Source§

fn get_or_set<CV, F, Fut, E>( &self, key: &str, load: F, options: impl Into<Option<CacheOptions>> + Send, ) -> impl Future<Output = Result<CV, E>> + Send
where CV: CacheValue, F: FnOnce() -> Fut + Send, Fut: Future<Output = Result<CV, E>> + Send, E: Send,

Returns the value under key, or runs load when there is none, then stores and returns what it gives. Of the callers on this store and its clones, one per key runs load; the others wait for it and get what it stored, or after lock_timeout_ms run load too. Other stores, such as those in other processes, load on their own, and a write made while load runs can be overwritten by its result. With refresh_threshold set, a value past that share of its TTL is loaded again by one caller, while the others get the cached value; if that load fails, its caller gets the cached value as long as the store still holds it. Read more
Source§

impl<Conn> Clone for RedisCacheStore<Conn>
where Conn: Clone + RedisConnection,

Source§

fn clone(&self) -> RedisCacheStore<Conn>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<Conn> Debug for RedisCacheStore<Conn>
where Conn: RedisConnection,

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<Conn> Freeze for RedisCacheStore<Conn>
where Conn: Freeze,

§

impl<Conn> RefUnwindSafe for RedisCacheStore<Conn>
where Conn: RefUnwindSafe,

§

impl<Conn> Send for RedisCacheStore<Conn>

§

impl<Conn> Sync for RedisCacheStore<Conn>

§

impl<Conn> Unpin for RedisCacheStore<Conn>
where Conn: Unpin,

§

impl<Conn> UnsafeUnpin for RedisCacheStore<Conn>
where Conn: UnsafeUnpin,

§

impl<Conn> UnwindSafe for RedisCacheStore<Conn>
where Conn: UnwindSafe,

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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