-
Notifications
You must be signed in to change notification settings - Fork 6
/
derive_async.rs
58 lines (50 loc) · 1.76 KB
/
derive_async.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use redis::{Client, AsyncCommands, ErrorKind, RedisError, RedisResult};
use redis_macros::{FromRedisValue, ToRedisArgs};
use serde::{Deserialize, Serialize};
/// Define structs to hold the data
/// Children structs don't have to implement FromRedisValue, ToRedisArgs, unless you want to use them as top level
/// They have to implement serde traits though!
#[derive(Debug, PartialEq, Serialize, Deserialize)]
enum Address {
Street(String),
Road(String),
}
/// Don't forget to implement serde traits and redis traits!
#[derive(Debug, PartialEq, Serialize, Deserialize, FromRedisValue, ToRedisArgs)]
struct User {
id: u32,
name: String,
addresses: Vec<Address>,
}
/// Show a simple async usage of redis_macros traits
/// Just derive the traits and forget them!
#[tokio::main]
async fn main() -> RedisResult<()> {
// Open new async connection to localhost
let client = Client::open("redis://localhost:6379")?;
let mut con = client.get_multiplexed_async_connection().await.map_err(|_| {
RedisError::from((
ErrorKind::InvalidClientConfig,
"Cannot connect to localhost:6379. Try starting a redis-server process or container.",
))
})?;
// Define the data you want to store in Redis.
let user = User {
id: 1,
name: "Ziggy".to_string(),
addresses: vec![
Address::Street("Downing".to_string()),
Address::Road("Abbey".to_string()),
],
};
// Set and get back the user in Redis asynchronously, no problem
con.set("user_async", &user).await?;
let stored_user: User = con.get("user_async").await?;
// You will get back the same data
assert_eq!(user, stored_user);
Ok(())
}
#[test]
fn test_derive_async() {
assert_eq!(main(), Ok(()));
}