redis_macros

Derive Macro FromRedisValue

Source
#[derive(FromRedisValue)]
{
    // Attributes available to this derive:
    #[redis_serializer]
}
Expand description

Derive macro for the redis crate’s FromRedisValue trait to allow parsing Redis responses to this type.

For more information see the redis_macros_derive crate: FromRedisValue Derive macro for the redis crate’s FromRedisValue trait to allow parsing Redis responses to this type.

NOTE: This trait requires serde’s Deserialize to also be derived (or implemented).

Simply use the #[derive(FromRedisValue, Deserialize)] before any structs (or serializable elements). This allows, when using Redis commands, to set this as the return type and deserialize from JSON automatically, while reading from Redis.

use redis_macros::{FromRedisValue};
use serde::{Deserialize};

#[derive(FromRedisValue, Deserialize)]
struct User { id: u32 }
  
con.set("user", &r#"{ "id": 1 }"#)?;
let user: User = con.get("user")?;  // => User { id: 1 }

If you want to use a different serde format, for example serde_yaml, you can set this with the redis_serializer attribute. The only restriction is to have the deserializer implement the from_str function.

use redis_macros::{FromRedisValue};
use serde::{Deserialize};

#[derive(FromRedisValue, Deserialize)]
#[redis_serializer(serde_yaml)]
struct User { id: u32 }

For more information see the isomorphic pair of this trait: ToRedisArgs.