Skip to main content

Crate fredis

Crate fredis 

Source
Expand description

§fredis

Crates.io Docs.rs License

An asynchronous, high-performance client for Redis and Valkey in Rust.

[!NOTE] fredis is an actively maintained fork of aembke/fred.rs. Because the upstream repository is no longer actively maintained, this fork was created to modernize the codebase, support Cloudflare Workers (TCP sockets), upgrade dependencies (such as rand 0.10, oneshot 0.2, rustls 0.23), migrate to Rust Edition 2024, and provide continuous maintenance and new features.


§Installation

Add fredis to your Cargo.toml:

[dependencies]
fredis = "10.1.0"

Or via cargo:

cargo add fredis

§Quick Example

use fredis::prelude::*;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Error> {
  let config = Config::from_url("redis://localhost:6379/1")?;
  let client = Builder::from_config(config)
    .with_connection_config(|config| {
      config.connection_timeout = Duration::from_secs(5);
      config.tcp = TcpConfig {
        nodelay: Some(true),
        ..Default::default()
      };
    })
    .build()?;

  client.init().await?;

  client.on_error(|(error, server)| async move {
    println!("{:?}: Connection error: {:?}", server, error);
    Ok(())
  });

  // Convert responses to common Rust types
  let foo: Option<String> = client.get("foo").await?;
  assert!(foo.is_none());

  client.set("foo", "bar", None, None, false).await?;

  // Or use turbofish to declare response types
  println!("Foo: {:?}", client.get::<String, _>("foo").await?);

  client.quit().await?;
  Ok(())
}

See the examples directory for more usage patterns.


§Highlights

  • Cloudflare Workers Support: Experimental support for Cloudflare Workers via TCP sockets (cloudflare feature).
  • Modern Rust: Built on Rust Edition 2024 (MSRV 1.85).
  • Protocol Flexibility: Full support for both RESP2 and RESP3 protocol modes.
  • Deployment Topologies: Works seamlessly with Clustered, Centralized, and Sentinel server topologies.
  • TLS & Security: Secure connections via native-tls or rustls (with aws-lc-rs or ring backends).
  • High Performance:
    • Automatic command pipelining across Tokio tasks
    • Zero-copy frame parsing powered by redis-protocol
    • Round-robin client pooling (Pool and DynamicPool)
    • Round-robin replica routing
  • Rich Feature Set:
    • Publish-Subscribe and keyspace event streams
    • Built-in mocking layer for testing
    • Lua scripts and functions
    • Transactions and Client Tracking (client-side caching)
    • Distributed tracing integration

§Feature Flags

§Client Features

NameDefaultDescription
transactionsxEnable a Transaction interface.
cloudflareEnable experimental support for Cloudflare Workers (TCP sockets).
enable-rustlsEnable TLS via rustls with the aws-lc-rs crypto backend.
enable-rustls-ringEnable TLS via rustls with the ring crypto backend.
enable-native-tlsEnable TLS via native-tls.
vendored-opensslEnable native-tls/vendored.
dynamic-poolEnable dynamic client pooling that scales connections based on metrics.
metricsEnable latency, network latency, and payload size tracking.
full-tracingEnable detailed tracing across all commands and network frames.
partial-tracingEnable lightweight tracing for top-level commands.
blocking-encodingOffload encoding/decoding to blocking tasks (useful for heavy payloads).
custom-reconnect-errorsCustomize error types that trigger automatic reconnection.
monitorEnable the MONITOR command interface.
sentinel-clientEnable direct communication with Sentinel nodes.
sentinel-authUse distinct authentication credentials for Sentinel nodes.
subscriber-clientEnable managed subscriber client for pub/sub channels.
serde-jsonEnable automatic conversion between Redis types and JSON via serde_json.
mocksEnable mocking interfaces for intercepting commands in unit/integration tests.
dnsOverride DNS lookup logic via hickory-resolver.
replicasRoute read commands to replica nodes.
default-nil-typesEnable looser parsing for nil values.
sha-1Enable hashing Lua scripts.
unix-socketsEnable Unix domain socket support.
credential-providerDynamically load auth credentials at runtime.
tcp-user-timeoutsConfigure TCP_USER_TIMEOUT on TCP sockets.
glommioEnable experimental Glommio runtime support (Linux only).

§Command Interfaces

Command interfaces start with i- to control which public command sets are compiled:

NameDefaultDescription
i-stdxEnable standard data structure interfaces (keys, hashes, lists, sets, streams, etc.).
i-allEnable all command interfaces listed below.
i-aclEnable ACL commands.
i-clientEnable CLIENT commands.
i-clusterEnable CLUSTER commands.
i-configEnable CONFIG commands.
i-geoEnable geospatial commands (GEOADD, GEODIST, etc.).
i-hashesEnable hash commands (HGET, HSET, etc.).
i-hyperloglogEnable HyperLogLog commands (PFADD, PFCOUNT, etc.).
i-keysEnable general key management commands (GET, SET, DEL, EXPIRE, etc.).
i-listsEnable list commands (LPUSH, RPOP, etc.).
i-memoryEnable MEMORY commands.
i-pubsubEnable Publish/Subscribe commands (SUBSCRIBE, PUBLISH, etc.).
i-scriptsEnable Lua scripting & functions (EVAL, FUNCTION, etc.).
i-serverEnable server administration commands (SHUTDOWN, BGSAVE, etc.).
i-setsEnable set commands (SADD, SMEMBERS, etc.).
i-slowlogEnable SLOWLOG commands.
i-sorted-setsEnable sorted set commands (ZADD, ZRANGE, etc.).
i-streamsEnable Redis streams commands (XADD, XREAD, XGROUP, etc.).
i-trackingEnable Client Tracking (client-side caching).

§Redis Stack & Module Features

NameDefaultDescription
i-redis-jsonEnable RedisJSON commands (JSON.SET, JSON.GET, etc.).
i-redisearchEnable RediSearch commands (FT.CREATE, FT.SEARCH, etc.).
i-time-seriesEnable Redis TimeSeries commands (TS.ADD, TS.RANGE, etc.).
i-redis-stackEnable all Redis Stack features (i-redis-json, i-redisearch, i-time-series).
i-hexpireEnable field-level hash expiration (HEXPIRE, HTTL, etc., Redis >= 7.4).

§License

Licensed under either of:

at your option.

Re-exports§

pub extern crate bytes;
pub extern crate bytes_utils;
pub extern crate native_tls;
pub extern crate rustls;
pub extern crate rustls_native_certs;
pub extern crate serde_json;
pub extern crate socket2;
pub extern crate tracing;

Modules§

clients
Redis client implementations.
error
Error structs returned by Redis commands.
interfaces
Traits that implement portions of the Redis interface.
mocksmocks
An interface for mocking commands.
monitormonitor
An interface to run the MONITOR command.
prelude
Convenience module to import a RedisClient, all possible interfaces, error types, and common argument types or return value types.
types
The structs and enums used by the Redis client.
util
Various client utility functions.

Macros§

cmd
Shorthand to create a CustomCommand.
json_quotei-redis-json
A helper macro to wrap a string value in quotes via the json macro.