This repository contains the code for an example project demonstrating asynchronous programming in Rust with the tokio
runtime and caching using the cached
library. This project is designed to complement the YouTube tutorial from Aarambh Dev Hub.
Click the image above to watch the detailed tutorial on YouTube!
- Introduction
- Project Structure
- Setup Instructions
- Running the Project
- Understanding the Code
- License
Asynchronous programming is crucial for building performant applications, especially when dealing with I/O-bound tasks. In this project, we demonstrate how to use Rust's async capabilities with the tokio
runtime and boost performance with caching using the cached
library.
Here's a brief overview of the project structure:
plaintext
Copy code
async_cached_example/
βββ Cargo.toml
βββ src/
βββ main.rs
Cargo.toml
: Contains the dependencies (tokio
andcached
).src/main.rs
: The main file where the asynchronous function and caching logic are implemented.
To set up this project on your local machine, follow these steps:
-
Clone the repository:
git clone https://github.com/AarambhDevHub/async_cached_example.git cd async-cached-example
-
Install the dependencies:
cargo build
-
Run the project:
cargo run
To see the asynchronous and caching code in action, simply run the project:
cargo run
You should see output that demonstrates how the fetch_data
function works asynchronously and how the cached version speeds up repeated calls.
In main.rs
, the fetch_data
function is an async function that simulates fetching data with a delay:
async fn fetch_data(id: u32) -> String {
println!("Fetching data for ID: {}", id);
sleep(Duration::from_secs(2)).await; // Simulate network delay
format!("Data for ID: {}", id)
}
The cached
library is used to cache the results of fetch_data
, preventing repeated calculations for the same input:
#[cached]
async fn fetch_data_cached(id: u32) -> String {
println!("Fetching data for ID: {}", id);
sleep(Duration::from_secs(2)).await;
format!("Data for ID: {}", id)
}
We can further customize the cache with a time-to-live (TTL) setting:
#[cached(time = 10)]
async fn fetch_data_cached_ttl(id: u32) -> String {
println!("Fetching data for ID: {}", id);
sleep(Duration::from_secs(2)).await;
format!("Data for ID: {}", id)
}
This setting ensures that cached data is invalidated after 10 seconds, forcing the function to fetch fresh data if called again after this period.
This project is licensed under the MIT License. See the LICENSE file for details.