1 个不稳定版本

0.1.0 2023年4月3日

#155 in #fields


用于 redis-om

MIT 许可

99KB
2.5K SLoC

redis-om

MIT licensed Build status Crates.io

A Rust/Redis ORM-style library that simplify the development process and reduce the amount of boilerplate code needed to build programs that leverage redis powerful capabilities and use cases.

状态: 工作进行中,已完全测试,可能存在破坏性更改,请关注

特性

  • ORM-style API定义/操作使用 derive 宏的Redis数据结构(例如哈希、JSON、流)。
  • Redis数据与rust对象之间的自动序列化/反序列化。
  • serde 兼容,例如使用 renamerename_allserde
  • 支持嵌套哈希数据类型(例如 list.1 或嵌套模型 account.balance 作为键)。

使用方法

路线图

  • 0.1.0
    • 使用最常见的方法允许用户定义和派生哈希模型
    • 使用最常见的方法允许用户定义和派生JSON模型
    • 允许用户使用管理器定义和派生流,并发布到/从中读取。
    • 支持用户选择异步或同步运行时。
  • 0.2.0
    • 支持多流管理器以允许用户组合多个 RedisModels
    • 支持使用 serde 序列化和反序列化 HashModel 复杂数据字段。
    • 支持 RedisSearch 并提供查询构建API。
    • .....
  • 0.3.0
    • 支持结构体字段和枚举值的验证(可能使用 validator 库)。
    • .....

入门

redis-om = { version = "*" }
# TLS support with async-std
redis-om = { version = "*", features = ["tls"] }
# async support with tokio
redis-om = { version = "*", features = ["tokio-comp"] }
# async support with async-std
redis-om = { version = "*", features = ["async-std-comp"] }
# TLS and async support with tokio
redis-om = { version = "*", features = ["tokio-native-tls-comp"] }
# TLS support with async-std
redis-om = { version = "*", features = ["async-std-tls-comp"] }

哈希

use redis_om::HashModel;

#[derive(HashModel, Debug, PartialEq, Eq)]
struct Customer {
    id: String,
    first_name: String,
    last_name: String,
    email: String,
    bio: Option<String>,
    interests: Vec<String>
}

// Now that we have a `Customer` model, let's use it to save customer data to Redis.

// First, we create a new `Customer` object:
let mut jane = Customer {
    id: "".into(), // will be auto generated when it's empty
    first_name: "Jane".into(),
    last_name: "Doe".into(),
    email: "[email protected]".into(),
    bio: Some("Open Source Rust developer".into()),
    interests: vec!["Books".to_string()],
};

// Get client
let client = redis_om::Client::open("redis://127.0.0.1/").unwrap();
// Get connection
let mut conn = client.get_connection().unwrap();

// We can save the model to Redis by calling `save()`:
jane.save(&mut conn).unwrap();

// Expire the model after 1 min (60 seconds)
jane.expire(60, &mut conn).unwrap();

// Retrieve this customer with its primary key
let jane_db = Customer::get(&jane.id, &mut conn).unwrap();

// Delete customer
Customer::delete(&jane.id, &mut conn).unwrap();

assert_eq!(jane_db, jane);

JSON

redis-om通过redis_om::JsonModel支持JSON数据类型。它要求类型必须继承自serde::Deserialize以及serde::Serialize

use redis_om::JsonModel;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
struct AccountDetails {
    balance: String,
}

#[derive(JsonModel, Deserialize, Serialize, Debug, PartialEq, Eq)]
struct Account {
    id: String,
    first_name: String,
    last_name: String,
    details: AccountDetails,
}

// Now that we have a `Account` model, let's use it to save account data to Redis.

// First, we create a new `Account` object:
let mut john = Account {
    id: "".into(), // will be auto generated when it's empty
    first_name: "John".into(),
    last_name: "Doe".into(),
    details: AccountDetails {
        balance: "1.5m".into(),
    }
};

// Get client
let client = redis_om::Client::open("redis://127.0.0.1/").unwrap();
// Get connection
let mut conn = client.get_connection().unwrap();

// We can save the model to Redis by calling `save()`:
john.save(&mut conn).unwrap();

// Expire the model after 1 min (60 seconds)
john.expire(60, &mut conn).unwrap();

// Retrieve this account with its primary key
let john_db = Account::get(&john.id, &mut conn).unwrap();

// Delete customer
Account::delete(&john.id, &mut conn).unwrap();

assert_eq!(john_db, john);

redis-om通过redis_om::StreamModel支持JSON数据类型。它要求任何嵌套类型都必须继承自redis_om::RedisTransportValue

use redis_om::{RedisTransportValue, StreamModel};

/// An enum of room service kind
#[derive(RedisTransportValue)]
pub enum RoomServiceJob {
    Clean,
    ExtraTowels,
    ExtraPillows,
    FoodOrder,
}

/// An enum of room service kind
#[derive(StreamModel)]
#[redis(key = "room")] // rename stream key in redis
pub struct RoomServiceEvent {
    status: String,
    room: usize,
    job: RoomServiceJob,
}

// Get client
let client = redis_om::Client::open("redis://127.0.0.1/").unwrap();
// Get connection
let mut conn = client.get_connection().unwrap();

// Create a new instance of Room service Event Manager with consumer group.
// Note: consumer name is auto generated,
// use RoomServiceEventManager::new_with_consumer_name, // for a custom name
let manager = RoomServiceEventManager::new("Staff");

// Ensure the consumer group
manager.ensure_group_stream(&mut conn).unwrap();

// Create new event
let event = RoomServiceEvent {
    status: "pending".into(),
    room: 3,
    job: RoomServiceJob::Clean,
};

// Publish the event to the RoomServiceEvent redis stream
RoomServiceEventManager::publish(&event, &mut conn).unwrap();

// Read with optional read_count: Option<usize>, block_interval: Option<usize>
let read = manager.read(None, None, &mut conn).unwrap();

// Get first incoming event
let incoming_event = read.first().unwrap();
// Get first incoming event data
let incoming_event_data = incoming_event.data::<RoomServiceEvent>().unwrap();
// Acknowledge that you received the event, so other in the consumers don't get it
RoomServiceEventManager::ack(manager.group_name(), &[&incoming_event.id], &mut conn).unwrap();

assert_eq!(incoming_event_data.room, event.room);

依赖项

~1.5MB
~36K SLoC