我使用 mio 在 Rust 中编写了一个多线程异步 HTTP 服务器。当我运行负载测试(使用围攻)时,服务器在第一次负载测试时工作正常,但是当负载测试完成时,对服务器的所有请求都开始失败。
使用一些日志记录,我注意到我获得的每个新连接都会accept()
立即收到一个挂断事件。服务器连接本身不会收到任何错误或挂断事件。
我在 OS X 10.11 El Capitan 上运行 Rust 1.12.0 和 mio 0.6
这是我的服务器的主要事件循环:
pub fn run(self) {
let poll = Poll::new().unwrap();
let server = TcpListener::bind(&SocketAddr::from_str(&self.host).unwrap()).unwrap();
poll.register(&server, SERVER, Ready::readable(), PollOpt::edge()).unwrap();
let mut events = Events::with_capacity(1024);
let mut next_conn: usize = 1;
let mut workers = Vec::new();
// Create worker threads.
for _ in 0..self.num_workers {
let (tx, rx) = channel();
let worker_handler = self.event_handler.duplicate();
thread::spawn(move || {
Self::process_events(rx, worker_handler);
});
workers.push(tx);
}
loop {
println!("Polling...");
match poll.poll(&mut events, None) {
Err(e) => panic!("Error during poll(): {}", e),
Ok(_) => {}
}
for event in events.iter() {
match event.token() {
SERVER => {
println!("Accepting..");
match server.accept() {
Ok((stream, _)) => {
println!("Registering new connection...");
match poll.register(&stream,
Token(next_conn),
Ready::readable(),
PollOpt::edge()) {
Err(e) => panic!("Error during register(): {}", e),
Ok(_) => {
println!("New connection on worker {} ",
next_conn % self.num_workers);
workers[next_conn % self.num_workers]
.send(Msg::NewConn(next_conn, stream))
.unwrap();
next_conn += 1;
}
}
}
Err(e) => panic!("Error during accept() : {}", e),
}
}
Token(id) => {
println!("Sending event on conn {} to worker {}",
id,
id % self.num_workers);
workers[id % self.num_workers]
.send(Msg::ConnEvent(id, event.kind()))
.unwrap();
}
}
}
}
}
fn process_events(channel: Receiver<Msg>, mut event_handler: Box<EventHandler>) {
loop {
let msg = channel.recv().unwrap();
match msg {
Msg::NewConn(id, conn) => {
event_handler.new_conn(id, conn);
}
Msg::ConnEvent(id, event) => {
event_handler.conn_event(id, event);
}
}
}
}
GitHub 上提供了我正在使用的示例 webapp 的完整代码。
负载测试命令:
siege -b -c10 -d10 -t20S http://localhost:8080