Open overvenus opened 7 years ago
I'm not sure it is better. API you propose have some drawbacks.
For example: does run
function ever exit? If run exists, am I allowed to call it again? How should I shutdown my server?
What if I need to start several servers? Now I can write:
fn main() {
let server1 = Server1::new(..);
let server2 = Server2::new(..)
wait_for_shutdown_signal(); // for SIGTERM or from control socket
// And that's it: both servers shut down.
}
It is harder to use when server is executed in run
function.
I think creating the server first and then running it makes more sense. We can see that mio, tokio-proto, hyper all create first then run.
What if I need to start several servers?
I don't think it is common to start multi servers in production. Listening one address for one server is enough, and we only need to register multi handlers for the server.
does run function ever exit?
It never exits.
If run exists, am I allowed to call it again?
No, if it exists, something must have gone wrong. In fact, I want it panic immediately, you know, fail fast.
What if I need to start several servers?
A simple solution would look like:
fn main() {
let server1 = Server1::new(..);
let server2 = Server2::new(..);
thread::spawn(move || {
server1.run();
});
thread::spawn(move || {
server2.run();
});
// ...
// So how do we shutdown servers?
}
In order to shutdown servers, they need a channel
.
pub struct Http2Server {
listen_addr: Mutex<SocketAddr>,
shutdown_tx: mpsc::Sender<()>,
shutdown_rx: Mutex<Option<mpsc::Receiver<()>>>,
state: Arc<Mutex<HttpServerState>>,
}
impl Http2Server {
pub fn run(&self) {
let shutdown_rx = {
let mut shutdown_rx = self.shutdown_rx.lock().unwrap();
shutdown_rx.take().expect("server is already running or stopped")
};
// listen and serve ...
}
pub fn shutdown_tx(&self) -> mpsc::Sender<()> {
self.shutdown_tx.clone()
}
}
fn main() {
let server1 = Server1::new(..);
let shutdown = server1.shutdown_tx();
let h = thread::spawn(move || {
server1.run();
});
// ...
shutdown.send(());
h.join().unwrap();
}
I know shutdown_tx()
seems weird, if you have any suggestions or comments, please let me know!
BTW I have already implement it in my branch, I'd like to send a PR if this API looks good to you. :grinning:
Hello @stepancheg
I saw
Http2Server::new()
creates a Http2Server and start it immediately.Could you separate
run_server_event_loop
fromnew
? Then the following code could be less confusing I think.Confuse me :confused::
Much clear :grinning::
Thanks!