Various implementations of a cache mechanism.
Code samples and slides of the presentation of March 14th, 2018, by Benoît Masson in the Golang Rennes context. These samples are given for demonstrating and exercising, and should not be used as such in production.
The cache interface to implement is defined as follows in src/cache/cache.go
:
type T interface {
Get(key string) ([]byte, bool)
Add(key string, content []byte)
Invalidate(key string)
}
This interface is implemented by 6 structures, in the corresponding file:
cache.none
: dummy implementation, does nothing;cache.nemory
: in-memory implementation based on Go’s maps;cache.syncMemory
: thread-safe version of the latter;cache.file
: persistent on-disk cache;cache.expirable
: in-memory cache, items are removed after their lifetime expires;cache.bounded
: bounded-size in-memory cache.
Basic tests for all cache implementations are defined in cache/cache_test.go
, and can be run using:
go test ./...
These implementations can also be tested individually using the given demonstration web server (folder server
).
This server replies with the reversed request path, with a 1 second delay if the result does not exist in cache, immediately otherwise.
Run it on default port 8888 with:
go install server && bin/server
and query it in another terminal with curl
:
curl http://localhost:8888/test && echo
curl http://localhost:8888/test/path && echo
curl http://localhost:8888/test/third/path && echo
The server uses the cache.New
function to initialize its cache, change the alias in file cache/cache.go
to use a different cache implementation.