redis_macros

Derive Macro ToRedisArgs

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

Derive macro for the redis crate’s ToRedisArgs trait to allow passing the type to Redis commands.

For more information see the redis_macros_derive crate: ToRedisArgs Derive macro for the redis crate’s ToRedisArgs trait to allow passing the type to Redis commands.

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

WARNING: This trait panics if the underlying serialization fails.

Simply use the #[derive(ToRedisArgs, Serialize)] before any structs (or serializable elements). This allows to pass this type to Redis commands like SET. The type will be serialized into JSON automatically while saving to Redis.

use redis_macros::{ToRedisArgs};
use serde::{Serialize};

#[derive(ToRedisArgs, Serialize)]
struct User { id: u32 }
  
con.set("user", User { id: 1 })?;
let user: String = con.get("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 restriciton is to have the serializer implement the to_string function.

use redis_macros::{ToRedisArgs};
use serde::{Serialize};

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

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