From 4c298ce18c3aeed7b6a8b9fade8ad7dbd931531e Mon Sep 17 00:00:00 2001 From: neon_arch Date: Tue, 29 Aug 2023 20:15:06 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=99=EF=B8=8F=20refactor:=20add=20code=20t?= =?UTF-8?q?o=20initialize=20redis=20cache=20struct=20only=20once=20(#180)(?= =?UTF-8?q?#178)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/server/routes.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/server/routes.rs b/src/server/routes.rs index 2fca2bc..8b4a523 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -16,6 +16,10 @@ use handlebars::Handlebars; use serde::Deserialize; use tokio::join; +// ---- Constants ---- +/// Initialize redis cache connection once and store it on the heap. +const REDIS_CACHE: async_once_cell::OnceCell = async_once_cell::OnceCell::new(); + /// A named struct which deserializes all the user provided search parameters and stores them. /// /// # Fields @@ -158,10 +162,17 @@ async fn results( page: u32, req: &HttpRequest, ) -> Result> { - //Initialize redis cache connection struct - let mut redis_cache = RedisCache::new(&config.redis_url, 5).await?; + let redis_cache: RedisCache = REDIS_CACHE + .get_or_init(async { + // Initialize redis cache connection pool only one and store it in the heap. + RedisCache::new(&config.redis_url, 5).await.unwrap() + }) + .await + .clone(); + // fetch the cached results json. - let cached_results_json = redis_cache.cached_json(&url).await; + let cached_results_json: Result> = + redis_cache.clone().cached_json(&url).await; // check if fetched cache results was indeed fetched or it was an error and if so // handle the data accordingly. match cached_results_json { @@ -205,6 +216,7 @@ async fn results( }; results.add_style(&config.style); redis_cache + .clone() .cache_results(&serde_json::to_string(&results)?, &url) .await?; Ok(results)