Skip to main content

Async Options

We have several example projects showing use of async database adapters:

Diesel

The current versions of Diesel (v1/v2) does not support asynchronous operations, so it is important to use the web::block function to offload your database operations to the Ntex runtime thread-pool.

You can create action functions that correspond to all the operations your app will perform on the database.


Now you should set up the database pool using a crate such as r2d2, which makes many DB connections available to your app. This means that multiple handlers can manipulate the DB at the same time, and still accept new connections. Simply store the pool in your app state. The state factory is called for each worker, every worker gets a clone of the pool, and the pool handles shared access for you.


Now, register the request handler with to_with_state(), the handler receives a reference to the app state as its first argument. Clone the pool and get a connection from it inside of a web::block closure. Then just call the action function with the necessary arguments and .await the result.

This example uses the ? operator, the BlockingError type implements WebResponseError and is rendered as a 500 (internal server error) response.


That's it! See the full example here: https://github.com/ntex-rs/examples/tree/master/diesel