advance-practice/spawning #888
Replies: 10 comments 12 replies
-
本节内容最开始,把之前的客户端代码放进
毕竟这部分内容是在第7章Cargo里才介绍到,这里最好补充一下简要说明和跳转链接吧 |
Beta Was this translation helpful? Give feedback.
-
Send约束rc的这个例子,感觉编译器把人掰弯过来后,再给你掰弯回去。毕竟前面借用检查都实现了Non-Lexical Lifetimes(NLL)--专门用于找到某个引用在作用域(})结束前就不再被使用的代码位置,这个地方是不是也可以更进一步呢? |
Beta Was this translation helpful? Give feedback.
-
本想尝试下异步的表现,可是怎么弄都是同步的逻辑。 use tokio; #[tokio::main] let s = say_to_world().await; async fn get_Song() -> String{ async fn sing(){ async fn dance(){ async fn say_to_world() -> String { |
Beta Was this translation helpful? Give feedback.
-
这个 用的是 rust 1.67.1 版本。 EDIT:搜了一下发现从 2015 年传承至今。rust-lang/rust#25165 |
Beta Was this translation helpful? Give feedback.
-
用 use std::collections::HashMap;
use tokio::net::{TcpListener, TcpStream};
use mini_redis::{Connection, Frame};
use mini_redis::Command::{Get,Set,self};
use tokio::sync::Mutex;
use std::sync::Arc;
#[tokio::main]
async fn main(){
let listener = TcpListener::bind("127.0.0.1:6379").await.expect("连接redis失败");
let mut db:Arc<Mutex<HashMap<String,Vec<u8>>>> = Arc::new(Mutex::new(HashMap::new()));
loop {
let (socket,_) = listener.accept().await.expect("监听失败");
let move_db = Arc::clone(&db);
tokio::spawn(async move {
process(socket, move_db).await;
});
}
}
async fn process(socket: TcpStream, db: Arc<Mutex<HashMap<String, Vec<u8>>>>) {
let mut connection = Connection::new(socket);
while let Some(frame) = connection.read_frame().await.unwrap() {
let response = match Command::from_frame(frame).unwrap() {
Set(cmd) => {
db.lock().await.insert(cmd.key().to_string(), cmd.value().to_vec());
Frame::Simple("OK".to_string())
}
Get(cmd) => {
match db.lock().await.get(cmd.key()) {
None => {
Frame::Null
}
Some(v) => {
Frame::Bulk(v.clone().into())
}
}
}
cmd => panic!("unimplemented commands {:?}",cmd),
};
connection.write_frame(&response).await.expect("Fail to write response");
}
} 然而这么做的缺点就是读写都共享同一把锁,要是可以做成无锁设计或者是写锁就好了..... |
Beta Was this translation helpful? Give feedback.
-
example 在运行的时候连接断开了- - 服务端要怎么样保持连接不断开呢? #[tokio::main]
} |
Beta Was this translation helpful? Give feedback.
-
mini-redis 好像不支持持久化 |
Beta Was this translation helpful? Give feedback.
-
求大佬解答,为什么服务端set返回值必须是大写的OK?感谢 |
Beta Was this translation helpful? Give feedback.
-
这里hashmap的编译器类型推导很有意思。在match里面,如果对换了Set和Get会导致编译不通过:只有db.insert才可以推导出类型,而先Get的话,db.get不知道是个什么。 然而写代码容易会先写出先get后set的习惯 |
Beta Was this translation helpful? Give feedback.
-
手写的朋友,如果set时遇到 Error: "unexpected frame: xxx",这时候检查一下set的返回值,必须是大写的OK。
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
advance-practice/spawning
https://course.rs/advance-practice/spawning.html
Beta Was this translation helpful? Give feedback.
All reactions