|
| 1 | +use ntex::util::ByteString; |
| 2 | + |
| 3 | +use super::{Command, CommandError}; |
| 4 | +use crate::codec::{Request, Response}; |
| 5 | + |
| 6 | +/// SELECT redis command |
| 7 | +/// |
| 8 | +/// Select the Redis logical database having the specified zero-based |
| 9 | +/// numeric index. |
| 10 | +/// |
| 11 | +/// ```rust |
| 12 | +/// use ntex_redis::{cmd, RedisConnector}; |
| 13 | +/// |
| 14 | +/// #[ntex::main] |
| 15 | +/// async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 16 | +/// let redis = RedisConnector::new("127.0.0.1:6379").connect().await?; |
| 17 | +/// |
| 18 | +/// // select db for current connection |
| 19 | +/// let success = redis.exec(cmd::Select(1)).await?; |
| 20 | +/// |
| 21 | +/// assert!(success); |
| 22 | +/// |
| 23 | +/// Ok(()) |
| 24 | +/// } |
| 25 | +/// ``` |
| 26 | +pub fn Select(db: u32) -> SelectCommand { |
| 27 | + SelectCommand(Request::Array(vec![ |
| 28 | + Request::from_static("SELECT"), |
| 29 | + Request::BulkInteger(db as i64), |
| 30 | + ])) |
| 31 | +} |
| 32 | + |
| 33 | +pub struct SelectCommand(Request); |
| 34 | + |
| 35 | +impl Command for SelectCommand { |
| 36 | + type Output = bool; |
| 37 | + |
| 38 | + fn to_request(self) -> Request { |
| 39 | + self.0 |
| 40 | + } |
| 41 | + |
| 42 | + fn to_output(val: Response) -> Result<Self::Output, CommandError> { |
| 43 | + match val { |
| 44 | + Response::String(val) => Ok(val == "OK"), |
| 45 | + _ => Ok(false), |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/// PING redis command |
| 51 | +/// |
| 52 | +/// This command is often used to test if a connection is still alive, |
| 53 | +/// or to measure latency. |
| 54 | +/// |
| 55 | +/// ```rust |
| 56 | +/// use ntex_redis::{cmd, RedisConnector}; |
| 57 | +/// |
| 58 | +/// #[ntex::main] |
| 59 | +/// async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 60 | +/// let redis = RedisConnector::new("127.0.0.1:6379").connect().await?; |
| 61 | +/// |
| 62 | +/// // ping connection |
| 63 | +/// let response = redis.exec(cmd::Ping()).await?; |
| 64 | +/// |
| 65 | +/// assert_eq!(&response, "PONG"); |
| 66 | +/// |
| 67 | +/// Ok(()) |
| 68 | +/// } |
| 69 | +/// ``` |
| 70 | +pub fn Ping() -> PingCommand { |
| 71 | + PingCommand(Request::Array(vec![Request::from_static("PING")])) |
| 72 | +} |
| 73 | + |
| 74 | +pub struct PingCommand(Request); |
| 75 | + |
| 76 | +impl Command for PingCommand { |
| 77 | + type Output = ByteString; |
| 78 | + |
| 79 | + fn to_request(self) -> Request { |
| 80 | + self.0 |
| 81 | + } |
| 82 | + |
| 83 | + fn to_output(val: Response) -> Result<Self::Output, CommandError> { |
| 84 | + match val { |
| 85 | + Response::String(val) => Ok(val), |
| 86 | + Response::Error(val) => Err(CommandError::Error(val)), |
| 87 | + _ => Err(CommandError::Output("Unknown response", val)), |
| 88 | + } |
| 89 | + } |
| 90 | +} |
0 commit comments