- Notifications
You must be signed in to change notification settings - Fork608
redis-rs/redis-rs
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Redis-rs is a high level Rust library for Redis, Valkey and any other RESP(Redis Serialization Protocol) compliant DB. It provides convenient accessto all Redis functionality through a very flexible but low-level API. Ituses a customizable type conversion trait so that any operation can returnresults in just the type you are expecting. This makes for a very pleasantdevelopment experience.
The crate is calledredis
and you can depend on it via cargo:
[dependencies]redis ="0.29.1"
Documentation on the library can be found atdocs.rs/redis.
To open a connection you need to create a client and then to fetch aconnection from it.
Many commands are implemented through theCommands
trait but manualcommand creation is also possible.
use redis::Commands;fnfetch_an_integer() -> redis::RedisResult<isize>{// connect to redislet client = redis::Client::open("redis://127.0.0.1/")?;letmut con = client.get_connection()?;// throw away the result, just make sure it does not faillet _:() = con.set("my_key",42)?;// read back the key and return it. Because the return value// from the function is a result for integer this will automatically// convert into one. con.get("my_key")}
Variables are converted to and from the Redis format for a wide variety of types(String
, num types, tuples,Vec<u8>
). If you want to use it with your own types,you can implement theFromRedisValue
andToRedisArgs
traits, or derive it with theredis-macros crate.
To enable asynchronous clients, enable the relevant feature in your Cargo.toml,tokio-comp
for tokio users orasync-std-comp
for async-std users.
# if you use tokioredis = { version = "0.29.1", features = ["tokio-comp"] }# if you use async-stdredis = { version = "0.29.1", features = ["async-std-comp"] }
When using a sync connection, it is recommended to use a connection pool in order to handledisconnects or multi-threaded usage. This can be done using ther2d2
feature.
redis = { version = "0.29.1", features = ["r2d2"] }
For async connections, connection pooling isn't necessary, unless blocking commands are used.TheMultiplexedConnection
is cloneable and can be used safely from multiple threads, so asingle connection can be easily reused. For automatic reconnections consider usingConnectionManager
with theconnection-manager
feature.Async cluster connections also don't require pooling and are thread-safe and reusable.
Multiplexing won't help if blocking commands are used since the server won't handle commandsfrom blocked connections until the connection is unblocked. If you want to be able to handlenon-blocking commands concurrently with blocking commands, you should send the blockingcommands on another connection.
To enable TLS support, you need to use the relevant feature entry in your Cargo.toml.Currently,native-tls
andrustls
are supported.
To usenative-tls
:
redis = { version = "0.29.1", features = ["tls-native-tls"] }# if you use tokioredis = { version = "0.29.1", features = ["tokio-native-tls-comp"] }# if you use async-stdredis = { version = "0.29.1", features = ["async-std-native-tls-comp"] }
To userustls
:
redis = { version = "0.29.1", features = ["tls-rustls"] }# if you use tokioredis = { version = "0.29.1", features = ["tokio-rustls-comp"] }# if you use async-stdredis = { version = "0.29.1", features = ["async-std-rustls-comp"] }
Addrustls
to dependencies
rustls = { version = "0.23", features = ["ring"] }
And then, before creating a connection, ensure that you install a crypto provider. For example:
rustls::crypto::ring::default_provider().install_default().expect("Failed to install rustls crypto provider");
Withrustls
, you can add the following feature flags on top of other feature flags to enable additional features:
tls-rustls-insecure
: Allow insecure TLS connectionstls-rustls-webpki-roots
: Usewebpki-roots
(Mozilla's root certificates) instead of native root certificates
then you should be able to connect to a redis instance using therediss://
URL scheme:
let client = redis::Client::open("rediss://127.0.0.1/")?;
To enable insecure mode, append#insecure
at the end of the URL:
let client = redis::Client::open("rediss://127.0.0.1/#insecure")?;
Deprecation Notice: If you were using thetls
orasync-std-tls-comp
features, please use thetls-native-tls
orasync-std-native-tls-comp
features respectively.
Support for Redis Cluster can be enabled by enabling thecluster
feature in your Cargo.toml:
redis = { version = "0.29.1", features = [ "cluster"] }
Then you can simply use theClusterClient
, which accepts a list of available nodes. Notethat only one node in the cluster needs to be specified when instantiating the client, thoughyou can specify multiple.
use redis::cluster::ClusterClient;use redis::Commands;fnfetch_an_integer() ->String{let nodes =vec!["redis://127.0.0.1/"];let client =ClusterClient::new(nodes).unwrap();letmut connection = client.get_connection().unwrap();let _:() = connection.set("test","test_data").unwrap();let rv:String = connection.get("test").unwrap();return rv;}
Async Redis Cluster support can be enabled by enabling thecluster-async
feature, alongwith your preferred async runtime, e.g.:
redis = { version = "0.29.1", features = [ "cluster-async", "tokio-std-comp" ] }
use redis::cluster::ClusterClient;use redis::AsyncCommands;asyncfnfetch_an_integer() ->String{let nodes =vec!["redis://127.0.0.1/"];let client =ClusterClient::new(nodes).unwrap();letmut connection = client.get_async_connection().await.unwrap();let _:() = connection.set("test","test_data").await.unwrap();let rv:String = connection.get("test").await.unwrap();return rv;}
Support for the RedisJSON Module can be enabled by specifying "json" as a feature in your Cargo.toml.
redis = { version = "0.29.1", features = ["json"] }
Then you can simply import theJsonCommands
trait which will add thejson
commands to all Redis Connections (not to be confused with justCommands
which only adds the default commands)
use redis::Client;use redis::JsonCommands;use redis::RedisResult;use redis::ToRedisArgs;// Result returns Ok(true) if the value was set// Result returns Err(e) if there was an error with the server itself OR serde_json was unable to serialize the booleanfnset_json_bool<P:ToRedisArgs>(key:P,path:P,b:bool) ->RedisResult<bool>{let client =Client::open("redis://127.0.0.1").unwrap();let connection = client.get_connection().unwrap();// runs `JSON.SET {key} {path} {b}` connection.json_set(key, path, b)?}
To parse the results, you'll need to useserde_json
(or some other json lib) to deserializethe results from the bytes. It will always be aVec
, if no results were found at the path it'llbe an emptyVec
. If you want to handle deserialization andVec
unwrapping automatically,you can use theJson
wrapper from theredis-macros crate.
To testredis
you're going to need to be able to test with the Redis Modules, to do thisyou must set the following environment variable before running the test script
REDIS_RS_REDIS_JSON_PATH
= The absolute path to the RedisJSON module (Eitherlibrejson.so
for Linux orlibrejson.dylib
for MacOS).Please refer to thislink to access the RedisJSON module:
If you want to develop on the library there are a few commands providedby the makefile:
To build the core crate:
$ cargo build --locked -p redis
To test:
Note:make test
requires cargo-nextest installed, to learn more about it please visithomepage of cargo-nextest.
$ make test
To run benchmarks:
$ make bench
To build the docs (require nightly compiler, seerust-lang/rust#43781):
$ make docs
We encourage you to runclippy
prior to seeking a merge for your work. The lints can be quite strict. Running this on your own workstation can save you time, since Travis CI will fail any build that doesn't satisfyclippy
:
$ cargo clippy --all-features --all --tests --examples -- -D clippy::all -D warnings
To run fuzz tests with afl, first install cargo-afl (cargo install -f afl
),then run:
$ make fuzz
If the fuzzer finds a crash, in order to reproduce it, run:
$ cd afl/<target>/$ cargo run --bin reproduce -- out/crashes/<crashfile>