高性能内存缓存
High performance in-memory & hybrid cache inspired by Caffeine.
Go 1.19+
go get github.com/Yiling-J/theine-goBuilder API
Theine provides two types of client, simple cache and loading cache. Both of them are initialized from a builder. The difference between simple cache and loading cache is: loading cache's Get method will compute the value using loader function when there is a miss, while simple cache client only return false and do nothing.
Loading cache uses singleflight to prevent concurrent loading to same key(thundering herd).
Entry Pool
Theine stores *Entry as the value in the hashmap, where each entry contains key, value, and metadata related to the policy. Before v0.6.0, Theine used a sync pool to automatically reuse evicted entries. This approach was beneficial for scenarios with heavy concurrent writes. If your system is already optimized for allocation, it should significantly reduce memory allocations. However, if cache writes are rare and GC is triggered often by other parts of your system, the sync pool becomes nearly useless.
And sync pool had a potential drawback: race conditions within the policy. Theine sends events to the policy asynchronously via channels/buffers, so there was a small chance that an event could be applied to the wrong entry if the entry was evicted and then reused by the pool.
To mitigate this, Theine rechecks the key first when updating the policy, but this behavior might be flagged by the race detector. Starting from v0.6.0, Theine introduced a new option called UseEntryPool, which defaults to false. If you are dealing with heavy concurrent writes and minimize allocations is crucial, you can enable this option.
API Details
simple cache:
…loading cache:
import "github.com/Yiling-J/theine-go"
// loader function: func(ctx context.Context, key K) (theine.Loaded[V], error)
// Loaded struct should include cache value, cost and ttl, which required by Set method
client, err := theine.NewBuilder[string, string](1000).Loading(
func(ctx context.Context, key string) (theine.Loaded[string], error) {
return theine.Loaded[string]{Value: key, Cost: 1, TTL: 0}, nil
},
).Build()
if err != nil {
panic(err)
}
Other builder options are same as simple cache(cost, doorkeeper, removal listener).
Client API
…Theine supports persisting the cache into io.Writer and restoring from io.Reader. Gob is used to encode/decode data, so make sure your key/value can be encoded by gob correctly first before using this feature.
func (c *Cache[K, V]) SaveCache(version uint64, writer io.Writer) error
func (c *Cache[K, V]) LoadCache(version uint64, reader io.Reader) error- Important: please LoadCache immediately after client created, or existing entries' TTL might be affected.
// save
f, err := os.Create("test")
err := client.SaveCache(0, f)
f.Close()
// load
f, err = os.Open("test")
require.Nil(t, err)
newClient, err := theine.NewBuilder[int, int](100).Build()
// load immediately after client created
err = newClient.LoadCache(0, f)
f.Close()Version number must be same when saving and loading, or LoadCache will return theine.VersionMismatch error. You can change the version number when you want to ignore persisted cache.
err := newClient.LoadCache(1, f)
// VersionMismatch is a global variable
if err == theine.VersionMismatch {
// ignore and skip loading
} else if err != nil {
// panic error
}Theine does not guarantee that caches from previous versions will be compatible after an upgrade, so it is highly recommended not to use the old persistence file when upgrading Theine.
When persisting cache, Theine roughly do:
When loading cache, Theine roughly do:
Theine will save checksum when persisting cache and verify checksum first when loading.
Source: https://github.com/maypok86/benchmarks
100% read (cpu 8/16/32)
…75% read (cpu 8/16/32)
…100% write (cpu 8/16/32)
…benchmem 100% write (cpu 32)
goos: linux
goarch: amd64
pkg: github.com/maypok86/benchmarks/throughput
cpu: Intel(R) Xeon(R) Platinum 8163 CPU @ 2.50GHz
BenchmarkCache/zipf_otter_reads=0%,writes=100%-32 80 B/op 1 allocs/op
BenchmarkCache/zipf_theine_reads=0%,writes=100%-32 0 B/op 0 allocs/op
BenchmarkCache/zipf_ristretto_reads=0%,writes=100%-32 112 B/op 3 allocs/op
zipf
s3
ds1
oltp
wiki CDN
Twitter Cache
SecondaryCache is the interface for caching data on a secondary tier, which can be a non-volatile media or alternate forms of caching such as sqlite. The purpose of the secondary cache is to support other ways of caching the object. It can be viewed as an extension of Theine’s current in-memory cache.
Currently, the SecondaryCache interface has one implementation inspired by CacheLib's Hybrid Cache.
type SecondaryCache[K comparable, V any] interface {
Get(key K) (value V, cost int64, expire int64, ok bool, err error)
Set(key K, value V, cost int64, expire int64) error
Delete(key K) error
HandleAsyncError(err error)
}If you plan to use a remote cache or database, such as Redis, as a secondary cache, keep in mind that the in-memory cache remains the primary source of truth. Evicted entries from memory are sent to the secondary cache. This approach differs from most tiered cache systems, where the remote cache is treated as the primary source of truth and is written to first.
NVM: https://github.com/Yiling-J/theine-nvm
Feel free to open an issue or ask question in discussions.
暂无开放 Issues,或尚未同步最近议题。