Using external io_context
Running single RESTinio server on external asio::io_context object
Sometimes it is necessary to have own instance of asio::io_context object which will be used for running RESTinio server and by some other operations. Since v.0.4.2 it is possible to pass a reference to asio::io_context instance to restinio::run() function. For example:
// External io_context.
asio::io_context io_context;
// Launch a single instance of RESTinio server on this context.
restinio::run(io_context,
restinio::on_this_thread()
.address(...)
.port(...)
.request_handler(
// Make io_context accessible from request-handler.
[&io_context](auto req) {
...
// io_context can be used for firing timers, for example.
auto timer = std::make_shared<asio::steady_timer>(io_context);
timer->expires_after(500ms);
timer->async_wait(...);
...
}));
Running several instances of RESTinio server on the same asio::io_context object
It is possible to run more than one server using the same io_context:
// External io_context.
asio::io_context io_context;
using server_t = restinio::http_server_t<>;
using settings_t = restinio::server_settings_t<>;
server_t srv1{
restinio::external_io_context( io_context ),
settings_t{}
.port( 8080 )
.address( "localhost" )
.request_handler( create_request_handler( "server1" ) ) };
server_t srv2{
restinio::external_io_context( io_context ),
settings_t{}
.port( 8081 )
.address( "localhost" )
.request_handler( create_request_handler( "server2" ) ) };
asio::signal_set break_signals{ io_context, SIGINT };
break_signals.async_wait(
[&]( const asio::error_code & ec, int ){
if( !ec )
{
srv1.close_sync();
srv2.close_sync();
}
} );
asio::post( io_context, [&] {
srv1.open_sync();
srv2.open_sync();
});
io_context.run();
Helper function restinio::external_io_context()
create such io_context holder that passes to server only its reference.
See also a full sample.