Redis client in Rust: complete guide to working with the redis-rs library

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

The redis-rs library: Rust client for Redis



redis-rs is the primary, mature, and most popular library for working with Redis from the Rust language. It provides both synchronous and asynchronous (based on tokio or async-std) APIs, supports clustering, pipelines, Pub/Sub, transactions, and Lua scripts. The library is distinguished by high performance, type safety, and ergonomics inherent to the Rust ecosystem.



Installation and connection



Add the dependency to Cargo.toml:



[dependencies]redis = { version = "0.25", features = ["tokio-comp"] }  # for async with tokio# orredis = "0.25"  # synchronous mode only


Basic connection to Redis (synchronous variant):



use redis::Commands;

fn main() -> redis::RedisResult<()> { let client = redis::Client::open("redis://127.0.0.1:6379/")?; let mut con = client.get_connection()?;

// Setting and getting a value con.set("key", "value")?; let val: String = con.get("key")?; println!("Received: {}", val);

Ok(())}


Main features



1. Typed commands

The library automatically converts Rust types to Redis types and back. Strings, numbers, tuples, vectors, as well as custom types via the FromRedisValue / ToRedisArgs trait are supported.



use redis::Commands;

let mut con = client.get_connection()?;let count: i32 = con.incr("counter", 2)?; // atomic incrementlet exists: bool = con.exists("nonexistent")?;let members: Vec<String> = con.smembers("set_key")?;


2. Pipelines

Pipelines allow sending multiple commands in a single network request, significantly speeding up batch operations.



use redis::Pipeline;

let mut pipe = Pipeline::new();pipe.cmd("SET").arg("a").arg(1).ignore();pipe.cmd("SET").arg("b").arg(2).ignore();pipe.cmd("GET").arg("a");let result: i32 = pipe.query(&mut con)?;println!("Value a: {}", result);


3. Asynchronous mode (async/await)

For high-load applications, use the async API based on tokio or async-std.



use redis::AsyncCommands;

#[tokio::main]async fn main() -> redis::RedisResult<()> { let client = redis::Client::open("redis://127.0.0.1:6379/")?; let mut con = client.get_multiplexed_async_connection().await?;

con.set("async_key", "async_value").await?; let val: String = con.get("async_key").await?; println!("Async: {}", val);

Ok(())}


4. Pub/Sub (publisher-subscriber)

Implementation of the Pub/Sub pattern for real-time message exchange.



use redis::{AsyncCommands, RedisResult};

#[tokio::main]async fn main() -> RedisResult<()> { let client = redis::Client::open("redis://127.0.0.1:6379/")?;

// Subscriber let mut pubsub = client.get_async_connection().await?.into_pubsub(); pubsub.subscribe("news").await?;

loop { let msg = pubsub.next_message().await?; println!("Received: {:?}", msg.get_payload::<String>()?); }}


5. Transactions (MULTI/EXEC)

Grouping commands into an atomic transaction.



use redis::Commands;

let mut con = client.get_connection()?;redis::transaction(&mut con, &["key1", "key2"], |con, pipe| { pipe.cmd("SET").arg("key1").arg(42).ignore(); pipe.cmd("INCR").arg("key2"); pipe.query(con)})?;


6. Clustering

To work with Redis Cluster, use redis::cluster::ClusterClient:

\

Recommendations