Return state data without cloning 🤔 #2832
Answered
by
jplatte
NiiightmareXD
asked this question in
Q&A
-
SummaryI'm building an experimental cache system to reduce database calls for the API. However, I'm facing a challenge: cloning the T data or Vec is necessary because the handler can't return an Arc. Are there any workarounds to avoid cloning? this is my current implementation: #[derive(Clone)]
pub struct CacheHandler {
connection: ConnectionManager,
posts_cache: Arc<RwLock<Option<Vec<Post>>>>,
sliders_cache: Arc<RwLock<Option<Sliders>>>,
}
impl CacheHandler {
pub async fn posts(&mut self) -> ServerResult<Vec<Post>> {
let posts = self.posts_cache.read().await.clone();
if let Some(posts) = posts {
Ok(posts)
} else {
let mut keys: Vec<String> = self.connection.keys("post:*").await?;
keys.sort_unstable();
let mut posts: Vec<Post> = Vec::new();
for key in keys {
let post: Post = self.connection.get(key).await?;
posts.push(post);
}
*self.posts_cache.write().await = Some(posts.clone());
Ok(posts)
}
}
pub async fn sliders(&mut self) -> ServerResult<Sliders> {
let sliders = self.sliders_cache.read().await.clone();
if let Some(sliders) = sliders {
Ok(sliders)
} else {
let sliders: Sliders = self.connection.get("sliders").await?;
*self.sliders_cache.write().await = Some(sliders.clone());
Ok(sliders)
}
}
} Ideally, the handler would return Arc. axum version0.7.5 |
Beta Was this translation helpful? Give feedback.
Answered by
jplatte
Jul 13, 2024
Replies: 1 comment 7 replies
-
What's the actual type you would want to return from your handler(s)? |
Beta Was this translation helpful? Give feedback.
7 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can actually do
Json<Arc<_>>
if you enable serde'src
feature: https://docs.rs/serde/latest/serde/trait.Serialize.html#impl-Serialize-for-Arc%3CT%3EAlternatively, you can use axum-extra's
ErasedJson
type and pass a reference to the arc-wrapped value to its constructor.Finally, we could probably make axum support
Arc<Json<_>>
as a response type, but I'm not sure how useful that would be here.