82 lines
2.5 KiB
Markdown
82 lines
2.5 KiB
Markdown
# Redis Client Module
|
|
|
|
A robust Redis client wrapper for Rust applications that provides connection management, automatic reconnection, and a simple interface for executing Redis commands.
|
|
|
|
## Features
|
|
|
|
- **Singleton Pattern**: Maintains a global Redis client instance, so we don't re-int all the time.
|
|
- **Connection Management**: Automatically handles connection creation and reconnection
|
|
- **Flexible Connectivity**:
|
|
- Tries Unix socket connection first (`$HOME/hero/var/myredis.sock`)
|
|
- Falls back to TCP connection (localhost) if socket connection fails
|
|
- **Database Selection**: Uses the `REDISDB` environment variable to select the Redis database (defaults to 0)
|
|
- **Error Handling**: Comprehensive error handling with detailed error messages
|
|
- **Thread Safety**: Safe to use in multi-threaded applications
|
|
|
|
## Usage
|
|
|
|
### Basic Usage
|
|
|
|
```rust
|
|
use crate::redisclient::execute;
|
|
use redis::cmd;
|
|
|
|
// Execute a simple SET command
|
|
let mut set_cmd = redis::cmd("SET");
|
|
set_cmd.arg("my_key").arg("my_value");
|
|
let result: redis::RedisResult<()> = execute(&mut set_cmd);
|
|
|
|
// Execute a GET command
|
|
let mut get_cmd = redis::cmd("GET");
|
|
get_cmd.arg("my_key");
|
|
let value: redis::RedisResult<String> = execute(&mut get_cmd);
|
|
if let Ok(val) = value {
|
|
println!("Value: {}", val);
|
|
}
|
|
```
|
|
|
|
### Advanced Usage
|
|
|
|
```rust
|
|
use crate::redisclient::{get_redis_client, reset};
|
|
|
|
// Get the Redis client directly
|
|
let client = get_redis_client()?;
|
|
|
|
// Execute a command using the client
|
|
let mut cmd = redis::cmd("HSET");
|
|
cmd.arg("my_hash").arg("field1").arg("value1");
|
|
let result: redis::RedisResult<()> = client.execute(&mut cmd);
|
|
|
|
// Reset the Redis client connection
|
|
reset()?;
|
|
```
|
|
|
|
## Environment Variables
|
|
|
|
- `REDISDB`: Specifies the Redis database number to use (default: 0)
|
|
- `HOME`: Used to determine the path to the Redis Unix socket
|
|
|
|
## Connection Strategy
|
|
|
|
1. First attempts to connect via Unix socket at `$HOME/hero/var/myredis.sock`
|
|
2. If socket connection fails, falls back to TCP connection at `redis://127.0.0.1/`
|
|
3. If both connection methods fail, returns an error
|
|
|
|
## Error Handling
|
|
|
|
The module provides detailed error messages that include:
|
|
- The connection method that failed
|
|
- The path to the socket that was attempted
|
|
- The underlying Redis error
|
|
|
|
## Testing
|
|
|
|
The module includes both unit tests and integration tests:
|
|
- Unit tests that mock Redis functionality
|
|
- Integration tests that require a real Redis server
|
|
- Tests automatically skip if Redis is not available
|
|
|
|
## Thread Safety
|
|
|
|
The Redis client is wrapped in an `Arc<Mutex<>>` to ensure thread safety when accessing the global instance. |