github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/mem/system.go (about)

     1  // Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
     2  
     3  package memutils
     4  
     5  import (
     6  	teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
     7  	"github.com/TeaOSLab/EdgeNode/internal/goman"
     8  	"github.com/shirou/gopsutil/v3/mem"
     9  	"time"
    10  )
    11  
    12  var systemTotalMemory = -1
    13  var systemMemoryBytes uint64
    14  var availableMemoryGB int
    15  
    16  func init() {
    17  	if !teaconst.IsMain {
    18  		return
    19  	}
    20  
    21  	_ = SystemMemoryGB()
    22  
    23  	goman.New(func() {
    24  		var ticker = time.NewTicker(10 * time.Second)
    25  		for range ticker.C {
    26  			stat, err := mem.VirtualMemory()
    27  			if err == nil {
    28  				availableMemoryGB = int(stat.Available >> 30)
    29  			}
    30  		}
    31  	})
    32  }
    33  
    34  // SystemMemoryGB 系统内存GB数量
    35  // 必须保证不小于1
    36  func SystemMemoryGB() int {
    37  	if systemTotalMemory > 0 {
    38  		return systemTotalMemory
    39  	}
    40  
    41  	stat, err := mem.VirtualMemory()
    42  	if err != nil {
    43  		return 1
    44  	}
    45  
    46  	systemMemoryBytes = stat.Total
    47  
    48  	availableMemoryGB = int(stat.Available >> 30)
    49  	systemTotalMemory = int(stat.Total >> 30)
    50  	if systemTotalMemory <= 0 {
    51  		systemTotalMemory = 1
    52  	}
    53  
    54  	setMaxMemory(systemTotalMemory)
    55  
    56  	return systemTotalMemory
    57  }
    58  
    59  // SystemMemoryBytes 系统内存总字节数
    60  func SystemMemoryBytes() uint64 {
    61  	return systemMemoryBytes
    62  }
    63  
    64  // AvailableMemoryGB 获取当下可用内存GB数
    65  func AvailableMemoryGB() int {
    66  	return availableMemoryGB
    67  }