From 82b070e7acbf0e345df99eeef0cb08d0ce3f6fa8 Mon Sep 17 00:00:00 2001 From: xfy Date: Wed, 17 Jun 2026 16:37:20 +0800 Subject: [PATCH] refactor(posts): use precise cache invalidation in create/update/delete --- src/api/posts/create.rs | 9 +++------ src/api/posts/delete.rs | 38 +++++++++++++++++++++++++++++++++++--- src/api/posts/update.rs | 10 +++++----- 3 files changed, 43 insertions(+), 14 deletions(-) diff --git a/src/api/posts/create.rs b/src/api/posts/create.rs index 58e7ac5..b83bf66 100644 --- a/src/api/posts/create.rs +++ b/src/api/posts/create.rs @@ -139,17 +139,14 @@ pub async fn create_post( tx.commit().await.map_err(AppError::tx)?; - // 写入成功后失效文章列表、标签与统计缓存。 + // 写入成功后按粒度失效相关缓存。 crate::cache::invalidate_post_lists(); crate::cache::invalidate_all_tags(); crate::cache::invalidate_post_stats(); // 失效按 slug 缓存,避免之前缓存的 404 继续命中。 crate::cache::invalidate_post_by_slug(&final_slug).await; - - // 失效该文章涉及的所有标签缓存。 - for tag_name in &tags_cleaned { - crate::cache::invalidate_posts_by_tag(tag_name).await; - } + // 失效该文章涉及的所有标签下文章列表缓存。 + crate::cache::invalidate_tag_posts_for(&tags_cleaned).await; Ok(CreatePostResponse { success: true, diff --git a/src/api/posts/delete.rs b/src/api/posts/delete.rs index b1f9043..d54df43 100644 --- a/src/api/posts/delete.rs +++ b/src/api/posts/delete.rs @@ -27,6 +27,34 @@ pub async fn delete_post(post_id: i32) -> Result = tag_rows.iter().map(|r| r.get(0)).collect(); + // 软删除:仅影响未被删除的文章。 let result = client .execute( @@ -45,14 +73,18 @@ pub async fn delete_post(post_id: i32) -> Result = old_tags + let all_tags_to_invalidate: Vec = old_tags .into_iter() .chain(tags_for_invalidation.into_iter()) + .collect::>() + .into_iter() .collect(); - for tag_name in &all_tags_to_invalidate { - crate::cache::invalidate_posts_by_tag(tag_name).await; - } + crate::cache::invalidate_tag_posts_for(&all_tags_to_invalidate).await; // 若 slug 发生变更,额外失效旧 slug 缓存。 if let Some(ref old) = old_slug {