crystal-lru-cache v1.0.3
LRU cache
💎 Key/value LRU cache that supports lifecycle, global size limit and expiration time.
LRU: Least Recently Used
lru-cache supports lifecycle, a global item size limit and an expiration time can be set for each item independently.
If a max_size is defined, the LRU cache can only contain max_size items. Beyond max_size, items are deleted from the oldest to the most recently used.
A caching system is a vital part, it must be simple to use, reliable and efficient. lru-cache is battle tested 👌
Installation
- Add the dependency to your
shard.yml
:
dependencies:
lru-cache:
github: nicolab/crystal-lru-cache
version: ~> 1.0.3 # Check the latest version!
- Run
shards install
Usage
require "lru-cache"
cache = LRUCache(String, String).new(max_size: 10_000)
cache.set("hello", "Hello Crystal!")
puts cache.get("hello") # => "Hello Crystal!"
# or
puts cache["hello"] # => "Hello Crystal!"
puts cache.has?("hello") # => true
# Time limit
cache.set("hello", "Hello Crystal!", Time.utc + 1.hour)
puts cache.expire_at "hello" # => Time.utc + 1.hour
# Deletes "hello" item
cache.delete "hello"
# Empties the cache
cache.clear
Lifecycle:
require "lru-cache"
class Cache(K, V) < LRUCache(K, V)
# Optional lifecycle method to be executed after setting an item (`add!` and `set`).
private def after_set(key : K, item : Tuple(V, Time?))
puts "after_set: #{key}"
pp item
end
# Optional lifecycle method to be executed after deleting an item (`delete`).
private def after_delete(key : K, item : Tuple(V, Time?)?)
puts "after_delete: #{key}"
pp item
end
# Optional lifecycle method to be executed after clearing all the cache (`clear`).
private def after_clear
puts "after_clear"
end
end
cache = Cache(String, String).new(max_size: 10_000)
cache.set("hello", "Hello Crystal!")
cache.set("foo", "bar")
cache.delete("foo")
cache.clear
📘 API doc
Development
Install dev dependencies:
shards install
Run:
crystal spec
Clean before commit:
crystal tool format
./bin/ameba
Contributing
- Fork it (https://github.com/Nicolab/crystal-lru-cache/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
LICENSE
MIT (c) 2021, Nicolas Talle.
Author
Repository
crystal-lru-cache
Owner
Statistic
- 8
- 2
- 0
- 4
- 1
- over 3 years ago
- February 27, 2021
License
Other
Links
Synced at
Sun, 17 Nov 2024 09:15:50 GMT
Languages