]> piware.de Git - learn-rust.git/blobdiff - tokio-tutorial-mini-redis/src/main.rs
tokio-tutorial-mini-redis: Shared global state
[learn-rust.git] / tokio-tutorial-mini-redis / src / main.rs
index a49865584dc70a67904e2e95634c4e5cbfe01a62..2488f033ead6e2808c08fe6f4499e3b0818f9d15 100644 (file)
@@ -1,17 +1,47 @@
-use mini_redis::{client, Result};
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
+use bytes::Bytes;
+use mini_redis::{Connection, Frame};
+use mini_redis::Command::{self, Get, Set};
+use tokio::net::{TcpListener, TcpStream};
+
+type Db = Arc<Mutex<HashMap<String, Bytes>>>;
 
 #[tokio::main]
-async fn main() -> Result<()> {
-    // Open a connection to the mini-redis address.
-    let mut client = client::connect("127.0.0.1:6379").await?;
+async fn main() {
+    let listener = TcpListener::bind("127.0.0.1:6379").await.unwrap();
+    let db: Db = Arc::new(Mutex::new(HashMap::new()));
 
-    // Set the key "hello" with value "world"
-    client.set("hello", "world".into()).await?;
+    loop {
+        // The second item contains the IP and port of the new connection
+        let (socket, _) = listener.accept().await.unwrap();
+        let db_i = db.clone();
+        tokio::spawn(async move { process(socket, db_i).await });
+    }
+}
 
-    // Get key "hello"
-    let result = client.get("hello").await?;
+async fn process(socket: TcpStream, db: Db) {
+    let mut connection = Connection::new(socket);
 
-    println!("got value from the server; result={:?}", result);
+    while let Some(frame) = connection.read_frame().await.unwrap() {
+        let response = match Command::from_frame(frame).unwrap() {
+            Set(cmd) => {
+                // The value is stored as `Vec<u8>`
+                db.lock().unwrap().insert(cmd.key().to_string(), cmd.value().clone());
+                Frame::Simple("OK".to_string())
+            }
+            Get(cmd) => {
+                if let Some(value) = db.lock().unwrap().get(cmd.key()) {
+                    Frame::Bulk(value.clone())
+                } else {
+                    Frame::Null
+                }
+            }
+            cmd => panic!("unimplemented {:?}", cmd),
+        };
 
-    Ok(())
+        // Write the response to the client
+        connection.write_frame(&response).await.unwrap();
+    }
 }