@@ -74,6 +74,36 @@ async fn main() {
7474}
7575```
7676
77+ You can also provide a custom TTL per key, if you use the ` with_meta_loader ` method.
78+ Below example will override the global 30s ttl with a 10s ttl.
79+ Yes, it doesn't make sense to override every key, so you should be having conditions there.
80+ ``` rust
81+ async fn main () {
82+ let duration : Duration = Duration :: from_secs (30 );
83+ let cache = LoadingCache :: with_meta_loader (TtlCacheBacking :: new (duration ), move | key : String | {
84+ async move {
85+ Ok (key . to_lowercase ())
86+ . with_meta (Some (TtlMeta :: from (Duration :: from_secs (10 ))))
87+ }
88+ });
89+ }
90+ ```
91+
92+ Additionally, the TTL backing allows you to customize the underlying backing. By default, it's using the
93+ ` HashMapBacking ` .
94+
95+ ``` rust
96+ async fn main () {
97+ let duration : Duration = Duration :: from_secs (30 );
98+ let cache = LoadingCache :: with_meta_loader (TtlCacheBacking :: with_backing (LruCacheBacking :: new (10 ), duration ), move | key : String | {
99+ async move {
100+ Ok (key . to_lowercase ())
101+ . with_meta (Some (TtlMeta :: from (Duration :: from_secs (10 ))))
102+ }
103+ });
104+ }
105+ ```
106+
77107## Own Backing
78108
79109To implement an own cache backing, simply implement the public ` CacheBacking ` trait from the ` backing ` mod.
@@ -82,11 +112,14 @@ To implement an own cache backing, simply implement the public `CacheBacking` tr
82112pub trait CacheBacking <K , V >
83113 where K : Eq + Hash + Sized + Clone + Send ,
84114 V : Sized + Clone + Send {
85- fn get (& mut self , key : & K ) -> Option <& V >;
86- fn set (& mut self , key : K , value : V ) -> Option <V >;
87- fn remove (& mut self , key : & K ) -> Option <V >;
88- fn contains_key (& self , key : & K ) -> bool ;
89- fn remove_if (& mut self , predicate : Box <dyn Fn ((& K , & V )) -> bool + Send + 'static >);
90- fn clear (& mut self );
115+ type Meta : Clone + Send ;
116+
117+ fn get_mut (& mut self , key : & K ) -> Result <Option <& mut V >, BackingError >;
118+ fn get (& mut self , key : & K ) -> Result <Option <& V >, BackingError >;
119+ fn set (& mut self , key : K , value : V , meta : Option <Self :: Meta >) -> Result <Option <V >, BackingError >;
120+ fn remove (& mut self , key : & K ) -> Result <Option <V >, BackingError >;
121+ fn contains_key (& mut self , key : & K ) -> Result <bool , BackingError >;
122+ fn remove_if (& mut self , predicate : Box <dyn Fn ((& K , & V )) -> bool + Send + Sync + 'static >) -> Result <Vec <(K , V )>, BackingError >;
123+ fn clear (& mut self ) -> Result <(), BackingError >;
91124}
92125```
0 commit comments