Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.


Introduction of depend on

Using the Redis-RS library, Cargo. Toml reads as follows:

[package]
edition = "2018"
name = "redis-test"
version = "0.1.0 from"

# [dependencies]

[dependencies.redis]
git = "https://github.com/mitsuhiko/redis-rs.git"

Copy the code

Connect the Redis

The Redis code is as follows:

    let client = redis::Client::open("redis://:password@ip:port/")? ;let mutcon = client.get_connection()? ;Copy the code

Single-machine mode Specifies the connection mode

The overall code is as follows:

extern crate redis;
use crate::redis::ConnectionLike;
use redis::Connection;

fn main() {
    let con = connection_redis().ok().unwrap();
    // Test whether Reids are connected successfully
    let is_open = con.is_open();
    println!("isOk: {}", is_open);
}

/** * Connect to connection_redis */
fn connection_redis() -> redis::RedisResult<Connection> {
    let client = redis::Client::open("redis://:password@ip:port/")? ;letcon = client.get_connection()? ;Ok(con)
}
Copy the code

Low-level commands

Low-level commands refer to operations performed directly using Reids commands.

Sample code:

/** * low-level command */
fn low_level_commands(con: &mut redis::Connection) -> redis::RedisResult<()> {
    // Add a key my_key value 42 to Redis
    let _: () = redis::cmd("SET").arg("my_key").arg(42).query(con)? ;// Get the value of my_key
    let my_key: i32 = redis::cmd("GET").arg("my_key").query(con)? ;println!("my_key: {}", my_key);

    // Hash operation
    let _: () = redis::cmd("HSET")
        .arg("books")
        .arg("java")
        .arg(1)
        .arg("python")
        .arg(2) .query(con)? ;let java_value: i32 = redis::cmd("HGET").arg("books").arg("java").query(con)? ;println!("java_value: {}", java_value);

    Ok(())}Copy the code

The result is as follows:

View after executionRedisAs you can seebooksThe data of

Senior command

Advanced commands are wrapped functions that make it easy to perform Redis operations. Advanced functions encapsulate common commands to facilitate the operation of various types of Redis data.

/** * Advanced command */
fn high_level_commands(con: &mut redis::Connection) -> redis::RedisResult<()> {
    // String operation
    con.set("count".42)? ;let count: i32 = con.get("count")? ;println!("count: {}", count);

    con.incr("count".100)? ;let incr_count: i32 = con.get("count")? ;println!("incr_count: {}", incr_count);

    // Hash operation
    con.hset("student"."name"."Zhang")? ; con.hset("student"."age".20)? ;let name: String = con.hget("student"."name")? ;println!("name: {}", name);

    / / the list action
    con.lpush("students"."Zhang")? ; con.lpush("students"."Bill")? ;let len: i32 = con.llen("students")? ;println!("students lengtth: {}", len);
    
    / / zset operations
    con.zadd("scores"."Zhang".60)? ; con.zadd("scores"."Bill".80)? ;// Find name with score between 70 and 100
    let names: HashSet<String> = con.zrangebyscore("scores".70.100)? ;for name in names {
        println!("name: {}", name);
    }

    Ok(())}Copy the code

The corresponding operation functions use different prefixes for different data types. For example, the hash type starts with H and the zset type starts with Z

The transaction

Transaction operations can be completed using the function redis:: Transaction. This function automatically monitors the key and then enters the transaction loop until it succeeds. Once successful, the results are returned.

fn transaction(con: &mut redis::Connection) -> redis::RedisResult<()> {
    let key = "transaction_test_key";
    con.set(key, 1)? ;let (new_val,): (isize,) = redis::transaction(con, &[key], |con, pipe| {
        let old_val: isize= con.get(key)? ;println!("old_val is: {}", old_val);
        pipe.incr(key, 2)
            .ignore()
            .incr(key, 100) .ignore() .get(key) .query(con) })? ;println!("new_val is: {}", new_val);

    Ok(())}Copy the code

Running results:

Complete code

extern crate redis;
use crate::redis::Commands;
use crate::redis::ConnectionLike;
use redis::Connection;
use std::collections::HashSet;

fn main() {
    let mut con = connection_redis().ok().unwrap();
    // Test whether Reids are connected successfully
    let is_open = con.is_open();
    println!("is_open: {}", is_open);
    println!(a);println!("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
    println!(a);// Low-level command
    let is_ok = low_level_commands(&mut con).is_ok();
    println!("low_level_commands exec is_ok: {}", is_ok);
    println!(a);println!("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
    println!(a);// Advanced command
    let is_ok = high_level_commands(&mut con).is_ok();
    println!("high_level_commands exec is_ok: {}", is_ok);
    println!(a);println!("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
    println!(a);let is_ok = transaction(&mut con).is_ok();
    println!("transaction is_ok: {}", is_ok);
}

/** * Connect to connection_redis */
fn connection_redis() -> redis::RedisResult<Connection> {
    let client = redis::Client::open(Redis: / / : [email protected]:6378 "/")? ;letcon = client.get_connection()? ;Ok(con)
}

/** * low-level command */
fn low_level_commands(con: &mut redis::Connection) -> redis::RedisResult<()> {
    // Add a key my_key value 42 to Redis
    let _: () = redis::cmd("SET").arg("my_key").arg(42).query(con)? ;// Get the value of my_key
    let my_key: i32 = redis::cmd("GET").arg("my_key").query(con)? ;println!("my_key: {}", my_key);

    // Hash operation
    let _: () = redis::cmd("HSET")
        .arg("books")
        .arg("java")
        .arg(1)
        .arg("python")
        .arg(2) .query(con)? ;let java_value: i32 = redis::cmd("HGET").arg("books").arg("java").query(con)? ;println!("java_value: {}", java_value);

    Ok(())}/** * Advanced command */
fn high_level_commands(con: &mut redis::Connection) -> redis::RedisResult<()> {
    // String operation
    con.set("count".42)? ;let count: i32 = con.get("count")? ;println!("count: {}", count);

    con.incr("count".100)? ;let incr_count: i32 = con.get("count")? ;println!("incr_count: {}", incr_count);

    // Hash operation
    con.hset("student"."name"."Zhang")? ; con.hset("student"."age".20)? ;let name: String = con.hget("student"."name")? ;println!("name: {}", name);

    / / the list action
    con.lpush("students"."Zhang")? ; con.lpush("students"."Bill")? ;let len: i32 = con.llen("students")? ;println!("students lengtth: {}", len);
    / / zset operations
    con.zadd("scores"."Zhang".60)? ; con.zadd("scores"."Bill".80)? ;// Find name with score between 70 and 100
    let names: HashSet<String> = con.zrangebyscore("scores".70.100)? ;for name in names {
        println!("name: {}", name);
    }

    Ok(())}/** * transaction */
fn transaction(con: &mut redis::Connection) -> redis::RedisResult<()> {
    let key = "transaction_test_key";
    con.set(key, 1)? ;let (new_val,): (isize,) = redis::transaction(con, &[key], |con, pipe| {
        let old_val: isize= con.get(key)? ;println!("old_val is: {}", old_val);
        pipe.incr(key, 2)
            .ignore()
            .incr(key, 100) .ignore() .get(key) .query(con) })? ;println!("new_val is: {}", new_val);

    Ok(())}Copy the code

Execution Result: