Redis
Learn to interface Rust with Redis.
We'll cover the following...
What is Redis?
Redis is an in-memory key-value store which is used as a database, cache, or message broker.
Having a K-V store is akin to having a server that stores HashMaps. However, it can have different kinds of values. It works primarily as an in-memory database, but it can also work as a service or in a cluster configuration. In addition to these uses, Redis can be scripted with Lua or extended with modules.
The values are specialized in different categories, with different commands to store and retrieve. The categories are bitmaps, geodata, hashes (that is, an entire HashMap as a value), lists, sets, sorted sets, and strings.
How to use Redis with Rust?
We can use the redis (or redis-rs
) crate to interface Rust with Redis.
[dependencies]
redis = "0.21.4"
Even if the Redis server lives in the memory of the same machine running the Rust program, we still need to connect to it as a server.
We can do that with the command redis::Client::open()
and the method get_connection()
on the client, as shown:
let client = redis::Client::open("redis://127.0.0.1:6379/")?;
let mut conn = client.get_connection()?;
Let’s see it in action by establishing a connection and setting and retrieving values.
Note: The Redis server must be up and running for the following code example to work. For the sake of this playground, we’ll use the custom
redis_connect()
function, which is not part of any Redis framework.
use redis::Commands;fn main() -> redis::RedisResult<()> {redis_connect(5)?; // Needed for this playground to worklet client = redis::Client::open("redis://127.0.0.1:6379/").expect("redis start failure");let mut conn = client.get_connection()?;let _ : () = conn.set("my_key", 42)?;let count : i32 = conn.get("my_key")?;println!("{}", count);Ok(())}
...