updated added cache
This commit is contained in:
1 parent
6d250c9c1a
commit
a5e28c5533
5 files changed
+271
-2
No files matched your search
+9
-1
@@ -3,13 +3,18 @@ use crate::model;
|
||||
use crate::state;
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use std::time::Instant;
|
||||
|
||||
pub async fn get_all_users_handler(
|
||||
State(state): State<state::AppState>,
|
||||
) -> Json<Vec<model::GetUserResponse>> {
|
||||
let key = "all_users".to_string();
|
||||
if let Some(cached_data) = state.cache.get(&key) {
|
||||
return Json(cached_data.0);
|
||||
}
|
||||
let storage_guard = state.storage.lock().await;
|
||||
let users: Vec<model::User> = storage_guard.values().cloned().collect();
|
||||
let mapped_users = users
|
||||
let mapped_users: Vec<model::GetUserResponse> = users
|
||||
.into_iter()
|
||||
.map(|user| model::GetUserResponse {
|
||||
id: user.id,
|
||||
@@ -19,6 +24,9 @@ pub async fn get_all_users_handler(
|
||||
is_superuser: user.is_superuser,
|
||||
})
|
||||
.collect();
|
||||
state
|
||||
.cache
|
||||
.insert(key, (mapped_users.clone(), Instant::now()));
|
||||
Json(mapped_users)
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ pub struct AddUserRequest {
|
||||
pub is_superuser: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GetUserResponse {
|
||||
pub id: String,
|
||||
pub username: String,
|
||||
|
||||
@@ -1,19 +1,29 @@
|
||||
use crate::config;
|
||||
use crate::db;
|
||||
use crate::model;
|
||||
use moka::sync::Cache;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub storage: db::UserStorage,
|
||||
pub config: config::Config,
|
||||
pub cache: Arc<Cache<String, (Vec<model::GetUserResponse>, Instant)>>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub async fn new() -> anyhow::Result<Self> {
|
||||
let config = config::Config::new().await?;
|
||||
let user_storage = db::init_user_storage().await;
|
||||
let cache = Cache::builder()
|
||||
.max_capacity(10_000) // максимальное количество записей
|
||||
.time_to_live(Duration::from_secs(300)) // TTL 5 минут
|
||||
.build();
|
||||
let state = AppState {
|
||||
storage: user_storage,
|
||||
config: config.clone(),
|
||||
cache: Arc::new(cache),
|
||||
};
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user