How to connect to Redis

You connect to Redis in Rust using the `redis` crate, which provides a high-level client that handles connection pooling, serialization, and command execution out of the box.

You connect to Redis in Rust using the redis crate, which provides a high-level client that handles connection pooling, serialization, and command execution out of the box. The standard approach involves adding the crate to your dependencies, creating a client instance with the Redis URL, and then obtaining a connection to execute commands.

First, add the dependency to your Cargo.toml:

[dependencies]
redis = { version = "0.25", features = ["tokio-comp"] }
tokio = { version = "1", features = ["full"] }

Here is a practical example using the async Tokio runtime, which is the standard for modern Rust applications. This snippet connects to a local Redis instance, sets a key, and retrieves it:

use redis::AsyncCommands;

#[tokio::main]
async fn main() -> redis::RedisResult<()> {
    // Connect to the default Redis URL (redis://127.0.0.1:6379)
    let client = redis::Client::open("redis://127.0.0.1/")?;
    let mut conn = client.get_async_connection().await?;

    // Set a key-value pair
    conn.set("my_key", "Hello, Redis!").await?;

    // Retrieve the value
    let value: String = conn.get("my_key").await?;
    
    println!("Retrieved value: {}", value);
    Ok(())
}

If you are working in a synchronous environment or need a blocking connection, you can use get_connection() instead of get_async_connection(), but async is generally preferred for performance in I/O-bound tasks. For production applications, you should wrap the client in a connection pool to manage multiple concurrent connections efficiently. The redis crate supports this via the ConnectionManager or by integrating with deadpool or bb8 for more granular control.

When connecting to Redis instances with authentication or on non-standard ports, simply update the URL string. For example, to connect to a password-protected instance on port 6380:

let client = redis::Client::open("redis://:mypassword@127.0.0.1:6380")?;

The crate automatically handles serialization for common Rust types (like String, i32, Vec, and HashMap) into Redis formats. If you encounter connection errors, verify that the Redis server is running and that the URL format is correct, including the protocol scheme (redis:// or rediss:// for TLS).