aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authoromagdy <omar.professional8777@gmail.com>2025-07-17 03:28:54 +0300
committeromagdy <omar.professional8777@gmail.com>2025-07-17 03:28:54 +0300
commit309067ef2e171fd0cfe2a3db5909f903d9aa15b0 (patch)
tree0db83413411961d9a80f66f4ea3e34beb30e3c7f
parentf13620eb1aa03ed31cb79c999f40d1af048b2656 (diff)
downloadredis-rust-309067ef2e171fd0cfe2a3db5909f903d9aa15b0.tar.xz
redis-rust-309067ef2e171fd0cfe2a3db5909f903d9aa15b0.zip
enhance: Added a cleanup thread that every 10 seconds cleans up null values that expire in the shared cache
-rw-r--r--src/main.rs23
1 files changed, 22 insertions, 1 deletions
diff --git a/src/main.rs b/src/main.rs
index 1dddb46..6905f11 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -5,7 +5,7 @@ use std::{
net::{TcpListener, TcpStream},
sync::{Arc, Mutex},
thread,
- time::{SystemTime, UNIX_EPOCH},
+ time::{Duration, SystemTime, UNIX_EPOCH},
};
mod resp_commands;
@@ -36,8 +36,27 @@ impl CacheEntry {
pub type SharedCache = Arc<Mutex<HashMap<String, CacheEntry>>>;
+fn spawn_cleanup_thread(cache: SharedCache) {
+ let cache_clone = cache.clone();
+ std::thread::spawn(move || {
+ loop {
+ std::thread::sleep(Duration::from_secs(10)); // Check every 10 seconds
+
+ let mut cache = cache_clone.lock().unwrap();
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_millis() as u64;
+
+ // Remove expired keys
+ cache.retain(|_, entry| entry.expires_at.map_or(true, |expiry| now <= expiry));
+ }
+ });
+}
+
fn handle_client(mut stream: TcpStream, cache: SharedCache) {
let mut buffer = [0; 512];
+
loop {
let _ = match stream.read(&mut buffer) {
Ok(0) => return, // connection closed
@@ -57,6 +76,8 @@ fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:6379").unwrap();
let cache: SharedCache = Arc::new(Mutex::new(HashMap::new()));
+ spawn_cleanup_thread(cache.clone());
+
for stream in listener.incoming() {
match stream {
Ok(stream) => {