Generic TTL cache with Eio
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

cache: add README content — usage examples, API overview

+49 -4
+49 -4
README.md
··· 1 - ## Cache - Generic TTL-based cache with Eio support 1 + ## Cache -- Generic TTL-based cache with Eio support 2 2 3 - A generic in-memory cache with configurable TTL (time-to-live), jitter to prevent thundering herd, and thread-safe access using Eio mutexes. 3 + A generic in-memory cache with configurable TTL (time-to-live), jitter to 4 + prevent thundering herd, and thread-safe access using Eio mutexes. 4 5 5 6 ## Installation 6 7 7 - `opam install cache` will install this library. 8 + ``` 9 + opam install cache 10 + ``` 11 + 12 + ## Usage 13 + 14 + ### String-keyed cache (pre-instantiated) 15 + 16 + ```ocaml 17 + let cache = Cache.String.create ~clock:(Eio.Stdenv.clock env) () in 18 + Cache.String.set cache "user:42" user_data; 19 + match Cache.String.get cache "user:42" with 20 + | Some data -> (* use cached data *) 21 + | None -> (* expired or missing *) 22 + ``` 23 + 24 + ### Compute-if-absent pattern 25 + 26 + ```ocaml 27 + (* Returns cached value or computes and caches it *) 28 + let data = Cache.String.get_or_compute cache "user:42" (fun () -> 29 + fetch_from_database 42) 30 + ``` 31 + 32 + ### Custom key type 8 33 9 - ## Documentation 34 + ```ocaml 35 + module IntCache = Cache.Make (struct 36 + type t = int 37 + let equal = Int.equal 38 + let hash = Hashtbl.hash 39 + end) 10 40 41 + let cache = IntCache.create ~clock ~base_ttl:300.0 ~jitter:0.1 () 42 + ``` 43 + 44 + ## API 45 + 46 + - `create ~clock ?base_ttl ?jitter ()` -- Create cache (default TTL: 60s, jitter: 0.2) 47 + - `get` / `set` / `remove` -- Basic operations 48 + - `get_or_compute` -- Compute-if-absent with automatic caching 49 + - `gc` -- Remove expired entries 50 + - `clear` -- Remove all entries 51 + - `stats` -- Returns `(total_entries, valid_entries)` 52 + 53 + ## Licence 54 + 55 + MIT