main.rs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. use tokio::net::{TcpListener, TcpStream};
  2. use mini_redis::{Connection, Frame};
  3. use bytes::Bytes;
  4. use std::collections::HashMap;
  5. use std::sync::{Arc, Mutex};
  6. type Db = Arc<Mutex<HashMap<String, Bytes>>>;
  7. #[tokio::main]
  8. async fn main() {
  9. // Bind the listener to the address
  10. let listener = TcpListener::bind("127.0.0.1:6379").await.unwrap();
  11. println!("Listening");
  12. let db = Arc::new(Mutex::new(HashMap::new()));
  13. loop {
  14. let (socket, _) = listener.accept().await.unwrap();
  15. // Clone the handle to the hash map.
  16. let db = db.clone();
  17. println!("Accepted");
  18. tokio::spawn(async move {
  19. process(socket, db).await;
  20. });
  21. }
  22. }
  23. async fn process(socket: TcpStream, db: Db) {
  24. use mini_redis::Command::{self, Get, Set};
  25. // Connection, provided by `mini-redis`, handles parsing frames from
  26. // the socket
  27. let mut connection = Connection::new(socket);
  28. while let Some(frame) = connection.read_frame().await.unwrap() {
  29. let response = match Command::from_frame(frame).unwrap() {
  30. Set(cmd) => {
  31. let mut db = db.lock().unwrap();
  32. db.insert(cmd.key().to_string(), cmd.value().clone());
  33. Frame::Simple("OK".to_string())
  34. }
  35. Get(cmd) => {
  36. let db = db.lock().unwrap();
  37. if let Some(value) = db.get(cmd.key()) {
  38. Frame::Bulk(value.clone())
  39. } else {
  40. Frame::Null
  41. }
  42. }
  43. cmd => panic!("unimplemented {:?}", cmd),
  44. };
  45. // Write the response to the client
  46. connection.write_frame(&response).await.unwrap();
  47. }
  48. }