Client

Struct Client 

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

High-level Redis client

Automatically handles:

  • Topology detection (Standalone vs Cluster)
  • MOVED and ASK redirects in cluster mode
  • Connection pooling (multiplexed or traditional)
  • Reconnection with exponential backoff

Implementations§

Source§

impl Client

Source

pub async fn connect(config: ConnectionConfig) -> RedisResult<Self>

Connect to Redis with the given configuration

This will automatically detect whether you’re connecting to a standalone Redis server or a Redis Cluster.

§Example
use redis_oxide::{Client, ConnectionConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = ConnectionConfig::new("redis://localhost:6379");
    let client = Client::connect(config).await?;
    Ok(())
}
Source

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

Get the value of a key

Source

pub async fn set( &self, key: impl Into<String>, value: impl Into<String>, ) -> RedisResult<bool>

Set the value of a key

Source

pub async fn set_ex( &self, key: impl Into<String>, value: impl Into<String>, expiration: Duration, ) -> RedisResult<bool>

Set the value of a key with expiration

Source

pub async fn set_nx( &self, key: impl Into<String>, value: impl Into<String>, ) -> RedisResult<bool>

Set the value of a key only if it doesn’t exist

Source

pub async fn del(&self, keys: Vec<String>) -> RedisResult<i64>

Delete one or more keys

Source

pub async fn exists(&self, keys: Vec<String>) -> RedisResult<i64>

Check if one or more keys exist

Source

pub async fn expire( &self, key: impl Into<String>, duration: Duration, ) -> RedisResult<bool>

Set a key’s time to live in seconds

Source

pub async fn ttl(&self, key: impl Into<String>) -> RedisResult<Option<i64>>

Get the time to live for a key

Source

pub async fn incr(&self, key: impl Into<String>) -> RedisResult<i64>

Increment the integer value of a key by one

Source

pub async fn decr(&self, key: impl Into<String>) -> RedisResult<i64>

Decrement the integer value of a key by one

Source

pub async fn incr_by( &self, key: impl Into<String>, increment: i64, ) -> RedisResult<i64>

Increment the integer value of a key by the given amount

Source

pub async fn decr_by( &self, key: impl Into<String>, decrement: i64, ) -> RedisResult<i64>

Decrement the integer value of a key by the given amount

Source

pub async fn hget( &self, key: impl Into<String>, field: impl Into<String>, ) -> RedisResult<Option<String>>

Get the value of a hash field

Source

pub async fn hset( &self, key: impl Into<String>, field: impl Into<String>, value: impl Into<String>, ) -> RedisResult<i64>

Set the value of a hash field

Source

pub async fn hdel( &self, key: impl Into<String>, fields: Vec<String>, ) -> RedisResult<i64>

Delete one or more hash fields

Source

pub async fn hgetall( &self, key: impl Into<String>, ) -> RedisResult<HashMap<String, String>>

Get all fields and values in a hash

Source

pub async fn hmget( &self, key: impl Into<String>, fields: Vec<String>, ) -> RedisResult<Vec<Option<String>>>

Get the values of multiple hash fields

Source

pub async fn hmset( &self, key: impl Into<String>, fields: HashMap<String, String>, ) -> RedisResult<String>

Set multiple hash fields to multiple values

Source

pub async fn hlen(&self, key: impl Into<String>) -> RedisResult<i64>

Get the number of fields in a hash

Source

pub async fn hexists( &self, key: impl Into<String>, field: impl Into<String>, ) -> RedisResult<bool>

Determine if a hash field exists

Source

pub async fn lpush( &self, key: impl Into<String>, values: Vec<String>, ) -> RedisResult<i64>

Push one or more values to the head of a list

Source

pub async fn rpush( &self, key: impl Into<String>, values: Vec<String>, ) -> RedisResult<i64>

Push one or more values to the tail of a list

Source

pub async fn lpop(&self, key: impl Into<String>) -> RedisResult<Option<String>>

Remove and return the first element of a list

Source

pub async fn rpop(&self, key: impl Into<String>) -> RedisResult<Option<String>>

Remove and return the last element of a list

Source

pub async fn lrange( &self, key: impl Into<String>, start: i64, stop: i64, ) -> RedisResult<Vec<String>>

Get a range of elements from a list

Source

pub async fn llen(&self, key: impl Into<String>) -> RedisResult<i64>

Get the length of a list

Source

pub async fn lindex( &self, key: impl Into<String>, index: i64, ) -> RedisResult<Option<String>>

Get an element from a list by its index

Source

pub async fn lset( &self, key: impl Into<String>, index: i64, value: impl Into<String>, ) -> RedisResult<()>

Set the value of an element in a list by its index

Source

pub async fn sadd( &self, key: impl Into<String>, members: Vec<String>, ) -> RedisResult<i64>

Add one or more members to a set

Source

pub async fn srem( &self, key: impl Into<String>, members: Vec<String>, ) -> RedisResult<i64>

Remove one or more members from a set

Source

pub async fn smembers( &self, key: impl Into<String>, ) -> RedisResult<HashSet<String>>

Get all members of a set

Source

pub async fn sismember( &self, key: impl Into<String>, member: impl Into<String>, ) -> RedisResult<bool>

Determine if a member is in a set

Source

pub async fn scard(&self, key: impl Into<String>) -> RedisResult<i64>

Get the number of members in a set

Source

pub async fn spop(&self, key: impl Into<String>) -> RedisResult<Option<String>>

Remove and return a random member from a set

Source

pub async fn srandmember( &self, key: impl Into<String>, ) -> RedisResult<Option<String>>

Get a random member from a set

Source

pub async fn zadd( &self, key: impl Into<String>, members: HashMap<String, f64>, ) -> RedisResult<i64>

Add one or more members to a sorted set

Source

pub async fn zrem( &self, key: impl Into<String>, members: Vec<String>, ) -> RedisResult<i64>

Remove one or more members from a sorted set

Source

pub async fn zrange( &self, key: impl Into<String>, start: i64, stop: i64, ) -> RedisResult<Vec<String>>

Get a range of members from a sorted set by index

Source

pub async fn zscore( &self, key: impl Into<String>, member: impl Into<String>, ) -> RedisResult<Option<f64>>

Get the score of a member in a sorted set

Source

pub async fn zcard(&self, key: impl Into<String>) -> RedisResult<i64>

Get the number of members in a sorted set

Source

pub async fn zrank( &self, key: impl Into<String>, member: impl Into<String>, ) -> RedisResult<Option<i64>>

Get the rank of a member in a sorted set (lowest to highest)

Source

pub async fn zrevrank( &self, key: impl Into<String>, member: impl Into<String>, ) -> RedisResult<Option<i64>>

Get the rank of a member in a sorted set (highest to lowest)

Source

pub fn pipeline(&self) -> Pipeline

Create a new pipeline for batching commands

Pipeline allows you to send multiple commands to Redis in a single network round-trip, which can significantly improve performance.

§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

let mut pipeline = client.pipeline();
pipeline.set("key1", "value1");
pipeline.set("key2", "value2");
pipeline.get("key1");

let results = pipeline.execute().await?;
println!("Pipeline results: {:?}", results);
Source

pub async fn transaction(&self) -> RedisResult<Transaction>

Create a new transaction for atomic command execution

Transactions allow you to execute multiple commands atomically using MULTI/EXEC. You can also use WATCH to monitor keys for changes.

§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

let mut transaction = client.transaction().await?;
transaction.set("key1", "value1");
transaction.set("key2", "value2");
transaction.incr("counter");

let results = transaction.exec().await?;
println!("Transaction results: {:?}", results);
Source

pub async fn publish( &self, channel: impl Into<String>, message: impl Into<String>, ) -> RedisResult<i64>

Publish a message to a Redis channel

Returns the number of subscribers that received the message.

§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

let subscribers = client.publish("news", "Breaking news!").await?;
println!("Message sent to {} subscribers", subscribers);
Source

pub async fn subscriber(&self) -> RedisResult<Subscriber>

Create a new subscriber for receiving messages from Redis channels

§Examples
use redis_oxide::{Client, ConnectionConfig};
use futures::StreamExt;

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

let mut subscriber = client.subscriber().await?;
subscriber.subscribe(vec!["news".to_string()]).await?;

while let Some(message) = subscriber.next_message().await? {
    println!("Received: {} on {}", message.payload, message.channel);
}
Source

pub async fn publisher(&self) -> RedisResult<Publisher>

Create a new publisher for sending messages to Redis channels

§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

let publisher = client.publisher().await?;
let subscribers = publisher.publish("news", "Breaking news!").await?;
println!("Message sent to {} subscribers", subscribers);
Source

pub async fn eval<T>( &self, script: &str, keys: Vec<String>, args: Vec<String>, ) -> RedisResult<T>

Execute a Lua script using EVAL

§Arguments
  • script - The Lua script source code
  • keys - List of Redis keys that the script will access (KEYS array in Lua)
  • args - List of arguments to pass to the script (ARGV array in Lua)
§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

let script = "return redis.call('GET', KEYS[1])";
let result: Option<String> = client.eval(
    script,
    vec!["mykey".to_string()],
    vec![]
).await?;
println!("Result: {:?}", result);
Source

pub async fn evalsha<T>( &self, sha: &str, keys: Vec<String>, args: Vec<String>, ) -> RedisResult<T>

Execute a Lua script using EVALSHA (script must be cached)

§Arguments
  • sha - The SHA1 hash of the script
  • keys - List of Redis keys that the script will access (KEYS array in Lua)
  • args - List of arguments to pass to the script (ARGV array in Lua)
§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

// First load the script
let script = "return redis.call('GET', KEYS[1])";
let sha = client.script_load(script).await?;

// Then execute using SHA
let result: Option<String> = client.evalsha(
    &sha,
    vec!["mykey".to_string()],
    vec![]
).await?;
println!("Result: {:?}", result);
Source

pub async fn script_load(&self, script: &str) -> RedisResult<String>

Load a Lua script into Redis cache

Returns the SHA1 hash of the script that can be used with EVALSHA.

§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

let script = "return 'Hello, World!'";
let sha = client.script_load(script).await?;
println!("Script loaded with SHA: {}", sha);
Source

pub async fn script_exists(&self, shas: Vec<String>) -> RedisResult<Vec<bool>>

Check if scripts exist in Redis cache

§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

let script = "return 'Hello'";
let sha = client.script_load(script).await?;

let exists = client.script_exists(vec![sha]).await?;
println!("Script exists: {:?}", exists);
Source

pub async fn script_flush(&self) -> RedisResult<()>

Flush all scripts from Redis cache

§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

client.script_flush().await?;
println!("All scripts flushed from cache");
Source

pub async fn xadd( &self, stream: impl Into<String>, id: impl Into<String>, fields: HashMap<String, String>, ) -> RedisResult<String>

Add an entry to a stream using XADD

§Arguments
  • stream - The name of the stream
  • id - The entry ID (“*” for auto-generation)
  • fields - The field-value pairs for the entry
§Examples
use redis_oxide::{Client, ConnectionConfig};
use std::collections::HashMap;

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

let mut fields = HashMap::new();
fields.insert("user_id".to_string(), "123".to_string());
fields.insert("action".to_string(), "login".to_string());

let entry_id = client.xadd("events", "*", fields).await?;
println!("Added entry: {}", entry_id);
Source

pub async fn xread( &self, streams: Vec<(String, String)>, count: Option<u64>, block: Option<Duration>, ) -> RedisResult<HashMap<String, Vec<StreamEntry>>>

Read entries from one or more streams using XREAD

§Arguments
  • streams - Vector of (stream_name, last_id) pairs
  • count - Maximum number of entries per stream (None for no limit)
  • block - Block timeout (None for non-blocking)
§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

// Non-blocking read
let streams = vec![("events".to_string(), "$".to_string())];
let messages = client.xread(streams, Some(10), None).await?;

for (stream, entries) in messages {
    for entry in entries {
        println!("Stream {}: {} -> {:?}", stream, entry.id, entry.fields);
    }
}
Source

pub async fn xrange( &self, stream: impl Into<String>, start: impl Into<String>, end: impl Into<String>, count: Option<u64>, ) -> RedisResult<Vec<StreamEntry>>

Read entries from a stream range using XRANGE

§Arguments
  • stream - The name of the stream
  • start - Start ID (inclusive, “-” for beginning)
  • end - End ID (inclusive, “+” for end)
  • count - Maximum number of entries to return
§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

// Get all entries
let entries = client.xrange("events", "-", "+", None).await?;
for entry in entries {
    println!("Entry {}: {:?}", entry.id, entry.fields);
}

// Get last 10 entries
let recent = client.xrange("events", "-", "+", Some(10)).await?;
Source

pub async fn xlen(&self, stream: impl Into<String>) -> RedisResult<u64>

Get the length of a stream using XLEN

§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

let length = client.xlen("events").await?;
println!("Stream has {} entries", length);
Source

pub async fn xgroup_create( &self, stream: impl Into<String>, group: impl Into<String>, id: impl Into<String>, mkstream: bool, ) -> RedisResult<()>

Create a consumer group using XGROUP CREATE

§Arguments
  • stream - The name of the stream
  • group - The name of the consumer group
  • id - The starting ID for the group (“$” for latest, “0” for beginning)
  • mkstream - Create the stream if it doesn’t exist
§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

// Create a consumer group starting from the latest messages
client.xgroup_create("events", "processors", "$", true).await?;
println!("Consumer group created");
Source

pub async fn xreadgroup( &self, group: impl Into<String>, consumer: impl Into<String>, streams: Vec<(String, String)>, count: Option<u64>, block: Option<Duration>, ) -> RedisResult<HashMap<String, Vec<StreamEntry>>>

Read from a consumer group using XREADGROUP

§Arguments
  • group - The consumer group name
  • consumer - The consumer name
  • streams - Vector of (stream_name, id) pairs (“>” for new messages)
  • count - Maximum number of entries per stream
  • block - Block timeout
§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

// Read new messages from the group
let streams = vec![("events".to_string(), ">".to_string())];
let messages = client.xreadgroup(
    "processors",
    "worker-1",
    streams,
    Some(1),
    Some(std::time::Duration::from_secs(1))
).await?;

for (stream, entries) in messages {
    for entry in entries {
        println!("Processing {}: {:?}", entry.id, entry.fields);
        // Acknowledge the message after processing
        client.xack(&stream, "processors", vec![entry.id]).await?;
    }
}
Source

pub async fn xack( &self, stream: impl Into<String>, group: impl Into<String>, ids: Vec<String>, ) -> RedisResult<u64>

Acknowledge messages using XACK

§Arguments
  • stream - The stream name
  • group - The consumer group name
  • ids - Vector of message IDs to acknowledge
§Examples
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://localhost:6379");
let client = Client::connect(config).await?;

// Acknowledge processed messages
let acked = client.xack("events", "processors", vec![
    "1234567890123-0".to_string(),
    "1234567890124-0".to_string(),
]).await?;
println!("Acknowledged {} messages", acked);
Source

pub fn topology_type(&self) -> TopologyType

Get the topology type

Trait Implementations§

Source§

impl Clone for Client

Source§

fn clone(&self) -> Client

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl Freeze for Client

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

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> 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> Same for T

Source§

type Output = T

Should always be Self
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 = 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