Skip to content

MemoryCache 上限控制 #95

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
QingsiLiu opened this issue Mar 1, 2025 · 1 comment
Open

MemoryCache 上限控制 #95

QingsiLiu opened this issue Mar 1, 2025 · 1 comment

Comments

@QingsiLiu
Copy link

我在一个小项目中使用了缓存相关,我没有使用 Redis,想仅仅使用 MemoryCache 即可,但我发现应用 MemoryCache 时内存会无序增长直到触发 OOM,所以我去看了相关的代码实现

源码中的初始化代码如下:

// NewMemoryCache create a memory cache
func NewMemoryCache(keyPrefix string, encode encoding.Encoding, newObject func() interface{}) Cache {
	// see: https://dgraph.io/blog/post/introducing-ristretto-high-perf-go-cache/
	//		https://www.start.io/blog/we-chose-ristretto-cache-for-go-heres-why/
	config := &ristretto.Config{
		NumCounters: 1e7,     // number of keys to track frequency of (10M).
		MaxCost:     1 << 30, // maximum cost of cache (1GB).
		BufferItems: 64,      // number of keys per Get buffer.
	}
	store, _ := ristretto.NewCache(config)
	return &memoryCache{
		client:    store,
		KeyPrefix: keyPrefix,
		encoding:  encode,
		newObject: newObject,
	}
}

关于 MemoryCache 每张表都是默认的 MaxCost 1GB,这一块没有提供自定义的能力,是我的用法有问题吗?还是最好提供内存使用限制呢,或者全局进行设置呢?

@zhufuyi
Copy link
Collaborator

zhufuyi commented Mar 2, 2025

已在 sponge v1.12.8 版本修复,默认参数限制最大内存 1GB,支持参数设置。

// 可以根据实际需要修改参数
cache.InitGlobalMemory(
	WithNumCounters(1e7),
	WithMaxCost(1<<30),
	WithBufferItems(64),
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants