mycommon-utils 0.2.2

Common utilities library for database operations, Redis caching and system utilities
Documentation

use sea_orm::prelude::DateTime;
use redis::{FromRedisValue, RedisWrite, ToRedisArgs, Value as RedisValue};
use serde::{Deserialize, Serialize};
use crate::database::BigIntPrimaryKey;
use crate::database::redis_util::RedisAsync;
use crate::error::{Error, Result};

// 消息推送类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum  MessagePushCategory {
    LOG(SysOpeLogCache)
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SysOpeLogCache {
    pub store_id: Option<BigIntPrimaryKey>,
    pub title: Option<String>,
    pub business_type: Option<i32>,
    pub method: Option<String>,
    pub request_method: Option<String>,
    pub operator_type: Option<i32>,
    pub oper_name: Option<String>,
    pub dept_name: Option<String>,
    pub oper_url: Option<String>,
    pub oper_ip: Option<String>,
    pub oper_location: Option<String>,
    pub oper_param: Option<String>,
    pub json_result: Option<String>,
    pub status: Option<i32>,
    pub error_msg: Option<String>,
    pub oper_time: Option<DateTime>,
    pub cost_time: Option<i64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct  MessageRedisCache {
    pub content: MessagePushCategory,
}

impl ToRedisArgs for MessageRedisCache {
    fn write_redis_args<W>(&self, out: &mut W) where W: ?Sized + RedisWrite,
    {
        let result = serde_json::to_string(self);
        if let Ok(result) = result {
            out.write_arg(result.as_bytes())
        }else {
            tracing::error!("TemplateMessageRedisCache::write_redis_args() failed");
        }
    }
}
impl FromRedisValue for MessageRedisCache {
    fn from_redis_value(v: RedisValue) -> std::result::Result<Self, redis::ParsingError> {
        match v {
            RedisValue::BulkString(bytes) => {
                let data = String::from_utf8(bytes.to_vec())?;
                serde_json::from_str::<MessageRedisCache>(&data)
                    .map_err(|_| redis::ParsingError::from("JSON parse error"))
            }
            _ => Err(redis::ParsingError::from("Unexpected value type")),
        }
    }
}


#[allow(dead_code)]
#[derive(Default,Clone)]
pub struct MessagePushStream{
    pub cache_name :String,
}

#[allow(dead_code)]
impl MessagePushStream {
    pub fn new(cache_name:  String) -> Self {
        MessagePushStream{
            cache_name,
        }
    }
    // stream 队列名称
    fn keys(&self) ->String {
        format!("{}",self.cache_name)
    }

    /// 添加到队列
    pub async fn publish(&self, item: MessageRedisCache) -> Result<String> {
        let queue_name = self.keys();
        RedisAsync::xadd_maxlen(&queue_name, 100000, "message", &item).await
            .map_err(|e| {
                tracing::error!("Failed to publish message: {:?}", e);
                Error::ErrorRedisConnectError()
            })
    }

}