缓存采用Arc,提高性能

This commit is contained in:
李运家 2024-06-20 17:01:46 +08:00
parent cf5c5286c0
commit 70162a37f6
5 changed files with 25 additions and 9 deletions

View File

@ -10,6 +10,22 @@ pub enum Role {
User, User,
} }
impl Role {
pub fn is_admin(&self) -> bool {
match self {
Role::Admin => true,
Role::User => false,
}
}
pub fn is_user(&self) -> bool {
match self {
Role::Admin => false,
Role::User => true,
}
}
}
impl Default for Role { impl Default for Role {
fn default() -> Self { fn default() -> Self {
Role::User Role::User

View File

@ -15,7 +15,7 @@ pub struct CacheAccount {
} }
lazy_static! { lazy_static! {
pub static ref LOGIN_CACHE: Cache<String, CacheAccount> = { pub static ref LOGIN_CACHE: Cache<String, Arc<CacheAccount>> = {
CacheBuilder::new(20480) CacheBuilder::new(20480)
.name("login_cache") .name("login_cache")
.eviction_policy(EvictionPolicy::lru()) .eviction_policy(EvictionPolicy::lru())

View File

@ -52,7 +52,7 @@ pub async fn authenticate_ctx(mut req: Request, next: Next) -> Response {
req.extensions_mut().insert( req.extensions_mut().insert(
Context { Context {
account: account.account.clone(), account: account.account.clone(),
token: account.token token: account.token.clone()
}); });
next.run(req).await next.run(req).await
}, },

View File

@ -59,10 +59,10 @@ pub async fn authenticate_google(
LOGIN_CACHE LOGIN_CACHE
.insert( .insert(
account.id.to_owned(), account.id.to_owned(),
CacheAccount { Arc::new(CacheAccount {
account: Arc::new(account.to_owned()), account: Arc::new(account.to_owned()),
token: Arc::new(token.to_owned()), token: Arc::new(token.to_owned()),
}, }),
) )
.await; .await;
@ -98,10 +98,10 @@ pub async fn refresh_token(
LOGIN_CACHE LOGIN_CACHE
.insert( .insert(
account.id.to_owned(), account.id.to_owned(),
CacheAccount { Arc::new(CacheAccount {
account, account,
token: Arc::new(refresh_token.token.to_owned()), token: Arc::new(refresh_token.token.to_owned()),
}, }),
) )
.await; .await;

View File

@ -39,7 +39,7 @@ pub async fn authenticate_with_password(
ACCOUNT_DISABLED ACCOUNT_DISABLED
))); )));
} }
if account.role != Role::Admin { if !account.role.is_admin() {
tracing::error!("账户不是管理员,无权限"); tracing::error!("账户不是管理员,无权限");
return Err(ResErr::perm(message!( return Err(ResErr::perm(message!(
context.get_lang_id(), context.get_lang_id(),
@ -53,10 +53,10 @@ pub async fn authenticate_with_password(
LOGIN_CACHE LOGIN_CACHE
.insert( .insert(
account.id.to_owned(), account.id.to_owned(),
CacheAccount { Arc::new(CacheAccount {
account: Arc::new(account.to_owned()), account: Arc::new(account.to_owned()),
token: Arc::new(token.to_owned()), token: Arc::new(token.to_owned()),
}, }),
) )
.await; .await;