Redis

How to Connect Redis with Rust

Rust has become one of the most popular and influential programming languages in the modern age. With the rise of Web Assembly, Rust could be powering the web in the decade.

This article will prepare for Web Assembly by learning how to connect Redis with our application. Keep in mind that this is a beginner and does not explore in-depth Rust or Redis topics.

Requirements

This tutorial assumes you have the latest Rust compiler and Redis server installed on your system.

We also assume you are not new to either Redis or Rust.

Installing Redis Client

To connect Redis with Rust, we need a Redis Rust client. For this tutorial, we will use redis-rs client. However, feel free to check out other clients.

Start by creating a new project:

$ cargo new redis_rust --bin

The above command will give a new project with all the files and directories we need.

To install the redis-rs package, edit the Cargo.toml file and add the following line:

[dependencies]
redis = "0.21.5"

Save and close the file.

Rust Connect Redis

Open the main.rs file in the src directory and add the code as shown below:

extern crate redis;
use redis::Commands;
fn main() {
    // create client
    let client = redis::Client::open("redis://127.0.0.1")?;
    let mut conn = cleint.get_connection()?;
}

In the above code, we start by importing the external create.

We create a client to the Redis server using the open method in the main function.

We then use the get_connection() function to tell the client to connect to the Redis server. This should return a connection object which we can use to send commands to the Redis server.

NOTE: If your Redis server is secured with a password, use the URL format as shown below:

redis://[<username>][:<password>@]<hostname>[:port][/<db>]

For example, to set the password for the default username:

redis://default:password@127.0.0.1:6379/0

Rust Set Key-Value Pair

The most basic operation is creating a new key-value pair when working with Redis. We can do this using a simple method as:

let _ : () = conn.set("year", 2022)?;

The above should create a new key called year with the value 2022 in the Redis server.

We can also create an expiring key with the code as shown below:

let _ : () = conn.setex("year", 2022, 60)?;

The code above creates a key that expires in 60 milliseconds.

Rust Get Value

To fetch the value associated with a key, we can use the code as shown:

println!("Year: {}", conn.get("year"));

Conclusion

This tutorial explores the fundamentals of connection Redis with Rust. You can check more at the resource provided below:

https://docs.rs/redis/latest/redis/

Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list