Files
cache_manager/manager/cache_benchmark_test.go
T

130 lines
3.0 KiB
Go
Raw Normal View History

2026-05-16 19:54:12 +08:00
package manager_test
import (
"context"
"fmt"
"os"
"testing"
"time"
"code.yun.ink/pkg/cache_manager/manager"
"github.com/redis/go-redis/v9"
)
// 本地缓存压测
type testStruct struct {
A int
B string
}
func getRedisClient() *redis.Client {
// 支持通过环境变量覆盖 redis 地址
addr := os.Getenv("TEST_REDIS_ADDR")
if addr == "" {
addr = "10.40.92.54:30379"
}
client := redis.NewClient(&redis.Options{
Addr: addr,
Password: "123000",
DB: 0,
})
return client
}
func BenchmarkCacheLocal_SetGet(b *testing.B) {
cache := manager.NewCacheLocal(time.Minute)
ctx := context.Background()
defer cache.Stop()
b.ResetTimer()
for i := 0; i < b.N; i++ {
key := "key" + fmt.Sprintf("%d", i)
val := testStruct{A: i, B: "val"}
_ = cache.Set(ctx, key, val, time.Minute, []int64{int64(i)})
var out testStruct
_ = cache.Get(ctx, key, &out)
}
}
func BenchmarkCacheLocal_Parallel(b *testing.B) {
cache := manager.NewCacheLocal(time.Minute)
ctx := context.Background()
defer cache.Stop()
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
key := "key" + fmt.Sprintf("%d", i)
val := testStruct{A: i, B: "val"}
_ = cache.Set(ctx, key, val, time.Minute, []int64{int64(i)})
var out testStruct
_ = cache.Get(ctx, key, &out)
i++
}
})
}
// Redis Hash 缓存压测
func BenchmarkCacheRedisHash_SetGet(b *testing.B) {
client := getRedisClient()
cache := manager.NewCacheRedisHash(client, "bench_hash", time.Hour)
ctx := context.Background()
b.ResetTimer()
for i := 0; i < b.N; i++ {
key := "key" + fmt.Sprintf("%d", i)
val := testStruct{A: i, B: "val"}
_ = cache.Set(ctx, key, val, time.Hour, []int64{int64(i)})
var out testStruct
_ = cache.Get(ctx, key, &out)
}
}
func BenchmarkCacheRedisHash_Parallel(b *testing.B) {
client := getRedisClient()
cache := manager.NewCacheRedisHash(client, "bench_hash", time.Hour)
ctx := context.Background()
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
key := "key" + fmt.Sprintf("%d", i)
val := testStruct{A: i, B: "val"}
_ = cache.Set(ctx, key, val, time.Hour, []int64{int64(i)})
var out testStruct
_ = cache.Get(ctx, key, &out)
i++
}
})
}
// Redis String 缓存压测
func BenchmarkCacheRedis_SetGet(b *testing.B) {
client := getRedisClient()
ctx := context.Background()
cache := manager.NewCacheRedis(ctx, client, "bench_str")
b.ResetTimer()
for i := 0; i < b.N; i++ {
key := "key" + fmt.Sprintf("%d", i)
val := testStruct{A: i, B: "val"}
_ = cache.Set(ctx, key, val, time.Hour, []int64{int64(i)})
var out testStruct
_ = cache.Get(ctx, key, &out)
}
}
func BenchmarkCacheRedis_Parallel(b *testing.B) {
client := getRedisClient()
ctx := context.Background()
cache := manager.NewCacheRedis(ctx, client, "bench_str")
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
key := "key" + fmt.Sprintf("%d", i)
val := testStruct{A: i, B: "val"}
_ = cache.Set(ctx, key, val, time.Hour, []int64{int64(i)})
var out testStruct
_ = cache.Get(ctx, key, &out)
i++
}
})
}