11use crate :: IOCached ;
2+ use redis:: Commands ;
23use serde:: de:: DeserializeOwned ;
34use serde:: Serialize ;
45use std:: marker:: PhantomData ;
@@ -217,7 +218,7 @@ where
217218 RedisCacheBuilder :: new ( prefix, ttl)
218219 }
219220
220- fn generate_key ( & self , key : & K ) -> String {
221+ fn generate_key ( & self , key : impl Display ) -> String {
221222 format ! ( "{}{}{}" , self . namespace, self . prefix, key)
222223 }
223224
@@ -345,6 +346,19 @@ where
345346 Some ( self . ttl )
346347 }
347348
349+ fn cache_clear ( & self ) -> Result < ( ) , RedisCacheError > {
350+ // `scan_match` takes `&mut self`, so we need two connection objects to scan and
351+ // delete...?
352+ let mut scan = self . pool . get ( ) ?;
353+ let mut delete = self . pool . get ( ) ?;
354+
355+ for key in scan. scan_match :: < _ , String > ( self . generate_key ( "*" ) ) ? {
356+ let ( ) = delete. del ( key) ?;
357+ }
358+
359+ Ok ( ( ) )
360+ }
361+
348362 fn cache_set_lifespan ( & mut self , ttl : Duration ) -> Option < Duration > {
349363 let old = self . ttl ;
350364 self . ttl = ttl;
@@ -365,6 +379,8 @@ where
365379mod async_redis {
366380 use std:: time:: Duration ;
367381
382+ use redis:: AsyncCommands ;
383+
368384 use super :: {
369385 CachedRedisValue , DeserializeOwned , Display , PhantomData , RedisCacheBuildError ,
370386 RedisCacheError , Serialize , DEFAULT_NAMESPACE , ENV_KEY ,
@@ -530,7 +546,7 @@ mod async_redis {
530546 AsyncRedisCacheBuilder :: new ( prefix, ttl)
531547 }
532548
533- fn generate_key ( & self , key : & K ) -> String {
549+ fn generate_key ( & self , key : impl Display ) -> String {
534550 format ! ( "{}{}{}" , self . namespace, self . prefix, key)
535551 }
536552
@@ -628,6 +644,21 @@ mod async_redis {
628644 }
629645 }
630646
647+ async fn cache_clear ( & self ) -> Result < ( ) , Self :: Error > {
648+ // `scan_match` takes `&mut self`, so we need two connection objects to scan and
649+ // delete...?
650+ let mut scan = self . connection . clone ( ) ;
651+ let mut delete = self . connection . clone ( ) ;
652+
653+ let mut scanner = scan. scan_match :: < _ , String > ( self . generate_key ( "*" ) ) . await ?;
654+
655+ while let Some ( key) = scanner. next_item ( ) . await {
656+ let ( ) = delete. del ( key) . await ?;
657+ }
658+
659+ Ok ( ( ) )
660+ }
661+
631662 /// Set the flag to control whether cache hits refresh the ttl of cached values, returns the old flag value
632663 fn cache_set_refresh ( & mut self , refresh : bool ) -> bool {
633664 let old = self . refresh ;
0 commit comments