Rayon

To run requests in parallel, we'll use the rayon crate, which provides a parallel iterator with the par_iter method. The parallel iterator divides a list into separate tasks that run across a pool of threads:

users.par_iter()
.map(|user| -> Result<(), failure::Error> {
let conn = pool.get()?;
create_user(&conn, &user)?;
Ok(())
})
.for_each(drop);

The parallel iterator returns items much like a traditional iterator. We can get a connection from the pool using the Pool::get method, and call the create_user function with a reference to a connection. We also ignore results here, and if any request fails, it will be skipped silently, as in the demonstration, we cannot take care of values that have not been inserted. Since we use multiple connections, we can't use transactions to roll back changes if any statement does fail.

The rayon crate looks really impressive and simple to use. You may ask: could you use this crate in microservices? The answer is: yes! But remember that to collect data, you have to call the for_each method, which blocks the current thread until all tasks are completed. If you call it in reactor's context (which we discussed in Chapter 5, Understanding Asynchronous Operations with  Futures Crate) in asynchronous Future, it will block the reactor for a while.

In the next section, we will rewrite this example for a MySQL database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.0.85