Crate redis_oxide

Crate redis_oxide 

Source
Expand description

High-performance async Redis client for Rust

redis-oxide is a Redis client library similar to StackExchange.Redis for .NET. It automatically detects whether you’re connecting to a standalone Redis server or a Redis Cluster, and handles MOVED/ASK redirects transparently.

§Features

  • 🚀 Automatic topology detection: Auto-recognizes Standalone Redis or Redis Cluster
  • 🔄 MOVED/ASK redirect handling: Automatically handles slot migrations in cluster mode
  • 🏊 Flexible connection strategies: Supports both Multiplexed connections and Connection Pools
  • 🛡️ Type-safe command builders: Safe API with builder pattern
  • Async/await: Fully asynchronous with Tokio runtime
  • 🔌 Automatic reconnection: Reconnects with exponential backoff
  • 📊 Comprehensive error handling: Detailed and clear error types
  • High test coverage: Extensive unit and integration tests

§Quick Start

§Basic Connection (Standalone)

use redis_oxide::{Client, ConnectionConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create configuration
    let config = ConnectionConfig::new("redis://localhost:6379");
     
    // Connect (automatically detects topology)
    let client = Client::connect(config).await?;
     
    // SET and GET
    client.set("mykey", "Hello, Redis!").await?;
    if let Some(value) = client.get("mykey").await? {
        println!("Value: {}", value);
    }
     
    Ok(())
}

§Redis Cluster Connection

use redis_oxide::{Client, ConnectionConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Provide multiple seed nodes
    let config = ConnectionConfig::new(
        "redis://node1:7000,node2:7001,node3:7002"
    );
     
    let client = Client::connect(config).await?;
     
    // Client automatically handles MOVED redirects
    client.set("key", "value").await?;
     
    Ok(())
}

§Handling MOVED Redirects

When encountering a MOVED error (e.g., MOVED 9916 10.90.6.213:6002), the library will:

  1. ✅ Parse the error message and extract slot number and target node
  2. ✅ Automatically update slot mapping
  3. ✅ Create new connection to target node if needed
  4. ✅ Automatically retry the command (up to max_redirects times)
use redis_oxide::{Client, ConnectionConfig};

let config = ConnectionConfig::new("redis://cluster:7000")
    .with_max_redirects(5); // Allow up to 5 redirects

let client = Client::connect(config).await?;

// If encountering "MOVED 9916 10.90.6.213:6002",
// client automatically retries command to 10.90.6.213:6002
let value = client.get("mykey").await?;

§Supported Commands

§String Operations

// GET
let value: Option<String> = client.get("key").await?;

// SET
client.set("key", "value").await?;

// SET with expiration
client.set_ex("key", "value", Duration::from_secs(60)).await?;

// SET NX (only if key doesn't exist)
let set: bool = client.set_nx("key", "value").await?;

// DELETE
let deleted: i64 = client.del(vec!["key1".to_string(), "key2".to_string()]).await?;

// EXISTS
let exists: i64 = client.exists(vec!["key".to_string()]).await?;

// EXPIRE
client.expire("key", Duration::from_secs(60)).await?;

// TTL
let ttl: Option<i64> = client.ttl("key").await?;

// INCR/DECR
let new_value: i64 = client.incr("counter").await?;
let new_value: i64 = client.decr("counter").await?;

// INCRBY/DECRBY
let new_value: i64 = client.incr_by("counter", 10).await?;
let new_value: i64 = client.decr_by("counter", 5).await?;

§Configuration

§Connection Configuration

use redis_oxide::{ConnectionConfig, TopologyMode};
use std::time::Duration;

let config = ConnectionConfig::new("redis://localhost:6379")
    .with_password("secret")           // Password (optional)
    .with_database(0)                  // Database number
    .with_connect_timeout(Duration::from_secs(5))
    .with_operation_timeout(Duration::from_secs(30))
    .with_topology_mode(TopologyMode::Auto) // Auto, Standalone, or Cluster
    .with_max_redirects(3);            // Max retries for cluster redirects

§Pool Configuration

§Multiplexed Connection (Default)

Uses a single connection shared between multiple tasks via mpsc channel. Suitable for most use cases.

use redis_oxide::{ConnectionConfig, PoolConfig, PoolStrategy};

let mut config = ConnectionConfig::new("redis://localhost:6379");
config.pool = PoolConfig {
    strategy: PoolStrategy::Multiplexed,
    ..Default::default()
};

§Connection Pool

Uses multiple connections. Suitable for very high workload with many concurrent requests.

use redis_oxide::{ConnectionConfig, PoolConfig, PoolStrategy};
use std::time::Duration;

let pool_config = PoolConfig {
    strategy: PoolStrategy::Pool,
    max_size: 20,                      // Max 20 connections
    min_idle: 5,                       // Keep at least 5 idle connections
    connection_timeout: Duration::from_secs(5),
};

let mut config = ConnectionConfig::new("redis://localhost:6379");
config.pool = pool_config;

Re-exports§

pub use client::Client;
pub use pipeline::Pipeline;
pub use pipeline::PipelineResult;
pub use pubsub::PubSubMessage;
pub use pubsub::Publisher;
pub use pubsub::Subscriber;
pub use script::Script;
pub use script::ScriptManager;
pub use sentinel::MasterInfo;
pub use sentinel::SentinelClient;
pub use sentinel::SentinelConfig;
pub use sentinel::SentinelEndpoint;
pub use streams::ConsumerGroupInfo;
pub use streams::ConsumerInfo;
pub use streams::PendingMessage;
pub use streams::ReadOptions;
pub use streams::StreamEntry;
pub use streams::StreamInfo;
pub use streams::StreamRange;
pub use transaction::Transaction;
pub use transaction::TransactionResult;
pub use crate::core::config::ConnectionConfig;
pub use crate::core::config::PoolConfig;
pub use crate::core::config::PoolStrategy;
pub use crate::core::config::ProtocolVersion;
pub use crate::core::config::TopologyMode;
pub use crate::core::error::RedisError;
pub use crate::core::error::RedisResult;
pub use crate::core::types::NodeInfo;
pub use crate::core::types::RedisValue;
pub use crate::core::types::SlotRange;
pub use crate::core::value::RespValue;
pub use crate::protocol::ProtocolNegotiation;
pub use crate::protocol::ProtocolNegotiator;
pub use crate::protocol::Resp3Value;

Modules§

client
High-level Redis client
cluster
Redis Cluster support
commands
Command builders for Redis operations
connection
Connection management and topology detection
core
Core types and traits for redis-oxide Redis client (embedded)
pipeline
Pipeline support for batching Redis commands
pool
Connection pooling implementations
pool_optimized
Optimized connection pooling implementations
protocol
Redis protocol implementations
pubsub
Pub/Sub support for Redis
script
Lua scripting support for Redis
sentinel
Redis Sentinel support for high availability
streams
Redis Streams support for event sourcing and messaging
transaction
Transaction support for Redis