Skip to content

Commit f89d6bc

Browse files
committed
Rustifying redis example
1 parent 724fd8e commit f89d6bc

File tree

2 files changed

+14
-26
lines changed

2 files changed

+14
-26
lines changed

step06_redis/code/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,6 @@ edition = "2024"
44

55
[dependencies]
66
clap = { version = "4.0", features = ["derive"] }
7-
redis = { version = "0.25", features = ["tokio-comp"] }
7+
redis = { version = "0.29.2", features = ["tokio-comp"] }
88
tokio = { version = "1", features = ["full"] }
9+
anyhow = "1.0"

step06_redis/code/src/main.rs

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
use clap::Parser;
22
use redis::AsyncCommands;
3-
use std::future::Future;
43
use std::process::ExitCode;
4+
use anyhow::Result;
5+
use anyhow::anyhow;
56

67
#[derive(Parser)]
78
struct Args {
@@ -12,48 +13,34 @@ struct Args {
1213
mode: String,
1314
}
1415

15-
async fn run_check(args: &Args) -> Result<u8, redis::RedisError> {
16+
async fn try_check(args: &Args) -> Result<()> {
1617
let _ = redis::Client::open(args.redis.to_string())?.get_multiplexed_async_connection().await?;
1718
println!("Redis is available.");
18-
Ok(0)
19+
Ok(())
1920
}
2021

21-
async fn run_test(args: &Args) -> Result<u8, redis::RedisError> {
22+
async fn try_test(args: &Args) -> Result<()> {
2223
let client = redis::Client::open(args.redis.to_string())?;
2324
let mut con = client.get_multiplexed_async_connection().await?;
2425

25-
let _: () = con.set("key", "value").await.expect("failed");
26+
let _: () = con.set("key", "value").await?;
2627
let val: String = con.get("key").await?;
2728

2829
println!("Got value: {}", val);
2930

30-
if val == "value" { Ok(0) } else { Ok(1) }
31-
}
32-
33-
async fn run_arm<'a, F, RETVAL>(f: F, args: &'a Args) -> ExitCode
34-
where
35-
F: FnOnce(&'a Args) -> RETVAL,
36-
RETVAL: Future<Output = Result<u8, redis::RedisError>>,
37-
{
38-
let result = f(&args).await;
39-
ExitCode::from(match result {
40-
Ok(code) => code,
41-
_ => {
42-
println!("Something failed, or Redis is not available.");
43-
1
44-
}
45-
})
31+
(val == "value").then(|| ()).ok_or(anyhow!("Wrong value"))
4632
}
4733

4834
#[tokio::main]
4935
async fn main() -> ExitCode {
5036
let args = Args::parse();
37+
5138
match args.mode.as_str() {
52-
"check" => run_arm(&run_check, &args).await,
53-
"test" => run_arm(&run_test, &args).await,
39+
"check" => try_check(&args).await.map_or(1, |_| 0),
40+
"test" => try_test(&args).await.map_or(1, |_| 0),
5441
_ => {
5542
println!("This `--mode` value is not supported.");
56-
ExitCode::from(1)
43+
1
5744
}
58-
}
45+
}.into()
5946
}

0 commit comments

Comments
 (0)