在设置进程内缓存的时候,除了过期时间,我们还需要限制缓存总大小的数量,防止出现OOM。所以,我们需要观测设置一定数量的缓存,内存的增长情况,以下是代码:

// 内存使用情况
func PrintMemUsage() {
    var m runtime.MemStats
    runtime.ReadMemStats(&m)
    fmt.Printf("Alloc = %v MiB", bToMb(m.Alloc))
    fmt.Printf("\tTotalAlloc = %v MiB", bToMb(m.TotalAlloc))
    fmt.Printf("\tSys = %v MiB", bToMb(m.Sys))
    fmt.Printf("\tNumGC = %v\n", m.NumGC)
}

// 转国际标(兆字节)
func bToMb(b uint64) uint64 {
    return b / 1024 / 1024
}

type Dog struct {
    Name string
}

func TestMapMem(t *testing.T) {
    m := map[string]Dog{}
    runtime.GC()
    PrintMemUsage()
    for i := 0; i < 1000000; i++ {
        d := Dog{Name: "name" + fmt.Sprintf("%d", i)}
        m[fmt.Sprintf("%d", i)] = d
    }
    runtime.GC()
    PrintMemUsage()
    z := m["1"]
    fmt.Println(z)
    runtime.GC()
    PrintMemUsage()
}

运行结果:
=== RUN   TestMapMem
Alloc = 0 MiB   TotalAlloc = 1 MiB  Sys = 11 MiB    NumGC = 1
Alloc = 103 MiB TotalAlloc = 201 MiB    Sys = 191 MiB   NumGC = 9
{name1}
Alloc = 0 MiB   TotalAlloc = 201 MiB    Sys = 191 MiB   NumGC = 10
--- PASS: TestMapMem (0.43s)
PASS

根据运行结果,可以看到,100w个Dog对象,占用的内存大概是103M