use futures::StreamExt;
use redis::{AsyncCommands, FromRedisValue, ToSingleRedisArg};
use crate::client::RedisClient;
use crate::error::Result;
#[derive(Debug, Clone)]
pub struct Message {
pub channel: String,
pub payload: Vec<u8>,
}
impl Message {
pub fn parse<T: FromRedisValue>(&self) -> Result<T> {
Ok(T::from_redis_value(redis::Value::BulkString(
self.payload.clone(),
))?)
}
pub fn as_str(&self) -> std::borrow::Cow<'_, str> {
String::from_utf8_lossy(&self.payload)
}
}
pub struct Subscription {
ps: redis::aio::PubSub,
client: redis::Client,
channels: Vec<String>,
patterns: Vec<String>,
}
impl Subscription {
pub async fn subscribe(&mut self, channel: &str) -> Result<()> {
self.ps.subscribe(channel).await?;
if !self.channels.iter().any(|c| c == channel) {
self.channels.push(channel.to_string());
}
Ok(())
}
pub async fn unsubscribe(&mut self, channel: &str) -> Result<()> {
self.ps.unsubscribe(channel).await?;
self.channels.retain(|c| c != channel);
Ok(())
}
pub async fn psubscribe(&mut self, pattern: &str) -> Result<()> {
self.ps.psubscribe(pattern).await?;
if !self.patterns.iter().any(|p| p == pattern) {
self.patterns.push(pattern.to_string());
}
Ok(())
}
pub async fn punsubscribe(&mut self, pattern: &str) -> Result<()> {
self.ps.punsubscribe(pattern).await?;
self.patterns.retain(|p| p != pattern);
Ok(())
}
pub fn subscribed_channels(&self) -> &[String] {
&self.channels
}
pub fn subscribed_patterns(&self) -> &[String] {
&self.patterns
}
pub async fn reconnect(&mut self) -> Result<()> {
self.reconnect_timeout(std::time::Duration::from_secs(5))
.await
}
pub async fn reconnect_timeout(&mut self, timeout: std::time::Duration) -> Result<()> {
if timeout > std::time::Duration::from_millis(crate::config::MAX_REDIS_RUNTIME_DURATION_MS)
{
return Err(crate::error::NasaRedisError::Config(format!(
"pubsub reconnect timeout 超过运行时上限 {}ms",
crate::config::MAX_REDIS_RUNTIME_DURATION_MS
)));
}
let build = async {
let mut ps = self.client.get_async_pubsub().await?;
for ch in &self.channels {
ps.subscribe(ch).await?;
}
for p in &self.patterns {
ps.psubscribe(p).await?;
}
Ok::<_, crate::error::NasaRedisError>(ps)
};
match tokio::time::timeout(timeout, build).await {
Ok(Ok(ps)) => {
self.ps = ps;
Ok(())
}
Ok(Err(e)) => Err(e),
Err(_) => Err(crate::error::NasaRedisError::Config(format!(
"pubsub reconnect 超时({}ms)——网络可能仍未恢复,请退避重试",
timeout.as_millis()
))),
}
}
pub async fn next_message(&mut self) -> Option<Message> {
let msg = self.ps.on_message().next().await?;
Some(Message {
channel: msg.get_channel_name().to_string(),
payload: msg.get_payload_bytes().to_vec(),
})
}
}
impl RedisClient {
pub async fn r#pub<V: ToSingleRedisArg + Send + Sync>(
&self,
channel: &str,
msg: V,
) -> Result<u64> {
let mut c = self.conn();
self.timed(c.publish(channel, msg)).await
}
pub async fn sub(&self, channels: &[&str]) -> Result<Subscription> {
let mut ps = self.raw_client().get_async_pubsub().await?;
for ch in channels {
ps.subscribe(*ch).await?;
}
Ok(Subscription {
ps,
client: self.raw_client().clone(),
channels: channels.iter().map(|s| s.to_string()).collect(),
patterns: Vec::new(),
})
}
pub async fn psubscribe(&self, patterns: &[&str]) -> Result<Subscription> {
let mut ps = self.raw_client().get_async_pubsub().await?;
for p in patterns {
ps.psubscribe(*p).await?;
}
Ok(Subscription {
ps,
client: self.raw_client().clone(),
channels: Vec::new(),
patterns: patterns.iter().map(|s| s.to_string()).collect(),
})
}
}