The code
Generate a new crate
Let’s start by generating a new Rust app:
$ cargo new my-redis
$ cd my-redis
Add dependencies
Next, open Cargo.toml
and add the following right below [dependencies]
:
tokio = { version = "1", features = ["full"] }
mini-redis = "0.4"
Write the code
Then, open main.rs
and replace the contents of the file with:
use mini_redis::{client, Result};
#[tokio::main]
pub async fn main() -> Result<()> {
// Open a connection to the mini-redis address.
let mut client = client::connect("127.0.0.1:6379").await?;
// Set the key "hello" with value "world"
client.set("hello", "world".into()).await?;
// Get key "hello"
let result = client.get("hello").await?;
println!("got value from the server; result={:?}", result);
Ok(())
}
Make sure the Mini-Redis server is running. In a separate terminal window, run:
$ mini-redis-server
Now, run the my-redis
application:
$ cargo run
got value from the server; result=Some(b"world")
Success!
You can find the full code here.