Rust, Software Development

Actix-Web With MySQL Using R2D2 For Connection Pool

R2D2 is a connection pool for Rust applications, e.g., Actix-Web, that use databases like MySQL. Opening and closing a database connection is an expensive operation. With connection pooling, the database connection creation happens once, and the application can reuse it numerous times without even closing it. Therefore, programs that use a connection pool are efficient and run faster.

Update Cargo.toml With Actix-Web And Others

First, let’s create a Rust application that is dependent on Actix-Web, MySQL, and R2D2. Update Cargo.toml as follows.

We need Actix-rt to use #[actix-rt::main]. It enables us to make the main function asyn fn.

MySQL Docker Compose

Then, we start a MySQL server Docker container via Docker Compose and create a Person table with sample data.

We will use these sample data:

Before moving on to the next section, please ensure the container is running, and MySQL has the Person table with data. Actix-web and R2D2 will use this MySQL database.

Add Codes For Actix-Web And R2D2

Then, we update the in our Rust application. First, import and use stuff as follows.

We then write a function that returns Option<Arc<Pool<MysqlConnectionManager>>> whose content represents an R2D2 pool of MySQL database connections. We store the pool as part of an application state within Actix-web.

Then, create a struct for Actix-web for application state.

Then, create an HTTP GET handler function. It runs whenever Actix-web receives a URL request for /persons/{id}. Also, it retrieves the R2D2 connection pool from the Actix-web application state and uses the id to query against the MySQL table for a specific person.

As an example, we use a simple SQL Select statement and only pick up the first record from the query result.

Lastly, let’s create the main function. As previously mentioned, it is an async fn because we are using #[actix_rt::main].

When we access http://localhost:8080/persons/1, the application should return a response that contains the name of the person in the database with person_id = 1.

We used Rust 1.41.0.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like