这是我的 Go 代码。我使用的是 1.13 版
一旦代码开始运行,内存消耗就会不断增加,永远不会减少。我不认为我正在创建新变量。我只是为所有存储重用全局变量。
我在网上读到 Go 中的 GC 应该每 2 分钟启动一次......?
编辑:我正在 Windows 任务管理器上监控程序的内存消耗。当程序开始运行时,内存从 ~5MB 开始,每分钟增加 0.3~0.5 MB。
package main
import (
"context"
"database/sql"
"encoding/csv"
"fmt"
"log"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"strings"
"time"
_ "github.com/denisenkom/go-mssqldb"
)
var path = os.Args[1]
var table = os.Args[4]
var backupPath = os.Args[2]
var location = os.Args[5]
var server = "localhost"
var port = 1433
var user = "###"
var password = "###"
var database = os.Args[3]
var ctx = context.Background()
var insertQuery = "INSERT INTO [" + database + "].[dbo].[" + table + "] ([meter_id],[time_stamp],[r_voltage],[y_voltage],[b_voltage],[ry_voltage],[yb_voltage],[br_voltage],[r_current],[y_current],[b_current],[kva],[kw],[kvar],[power_factor],[freq],[kwh],[run_hr],[updated_date]) VALUES"
var updateStatusQuery = "UPDATE EMS_Location_Status SET active='100',mailed='N',Updated_Date=getdate(),Error_desc='Data is coming from FTPS' where Location_Id ='" + location + "'"
var db *sql.DB
var connString = fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s;",
server, user, password, port, database)
var err error
var files []string
var tempInsertQuery string
var csvFile *os.File
var csvLines [][]string
var i int
var line []string
var point string
var processedFile []string
var fileName string
var iterFile string
var c = 10
func processFile(file string, table string) {
fmt.Println("Processing file...", file)
tempInsertQuery = insertQuery + " "
csvFile, err = os.Open(file)
if err != nil {
for err != nil {
fmt.Println("Encountered error in opening file.. trying again in 10 seconds.")
time.Sleep(10 * time.Second)
csvFile, err = os.Open(file)
}
fmt.Println(err)
}
csvLines, err = csv.NewReader(csvFile).ReadAll()
if err != nil {
fmt.Println(err)
}
for i, line = range csvLines {
if i == 0 {
continue
} else {
tempInsertQuery = tempInsertQuery + "("
for _, point = range line {
tempInsertQuery = tempInsertQuery + "'" + point + "'" + ","
}
tempInsertQuery = tempInsertQuery[0:len(tempInsertQuery)-1] + ", GETDATE()" + "), "
}
}
tempInsertQuery = tempInsertQuery[0 : len(tempInsertQuery)-2]
// Execute query
//fmt.Println(tempInsertQuery)
_, err = db.QueryContext(ctx, tempInsertQuery)
if err != nil {
fmt.Println(err)
return
}
_, err = db.QueryContext(ctx, updateStatusQuery)
if err != nil {
fmt.Println(err)
return
}
csvFile.Close()
fmt.Println("Done processing file ", file)
backupFile(file)
runtime.GC()
debug.FreeOSMemory()
}
func backupFile(file string) {
fmt.Println("Backing up...", file)
processedFile = strings.Split(file, "\\")
fileName = processedFile[len(processedFile)-1]
err = os.Rename(file, backupPath+fileName)
if err != nil {
log.Fatal(err)
}
}
func scanner(scanPath string, table string) {
err = filepath.Walk(scanPath, func(path string, info os.FileInfo, err error) error {
if strings.Contains(path, ".csv") {
files = append(files, path)
}
return nil
})
if err != nil {
panic(err)
}
for _, iterFile = range files {
time.Sleep(2 * time.Second)
processFile(iterFile, table)
}
files = files[:0]
}
func main() {
fmt.Println(connString)
// Create connection pool
db, err = sql.Open("sqlserver", connString)
if err != nil {
fmt.Println("Error creating connection pool: ", err.Error())
}
err = db.PingContext(ctx)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Printf("Connected to server!\n")
fmt.Printf("Initiating...\n")
for c > 0 {
scanner(path, table)
time.Sleep(1 * time.Second)
}
fmt.Println("Quitting..")
}
任何帮助,将不胜感激!谢谢。
最佳答案
Go 中的一般概念是任何实现 io.Closer
(有一个 Close()
方法),当你有一个不想再使用的值时,你应该调用它的 Close()
通常释放资源的方法,否则这些资源可能不会立即或根本不会(永远)释放。
您的 db.QueryContext()
电话是 sql.Conn.QueryContext()
返回 *sql.Rows
具有 Close()
的值方法。叫那个。目前您甚至没有存储返回的 sql.Rows
.
像这样做:
var rows *sql.Rows
rows, err = db.QueryContext(ctx, tempInsertQuery)
if err != nil {
fmt.Println(err)
return
}
if err2 := rows.Close(); err2 != nil {
fmt.Println("Error closing rows:", err2
}
将此应用于 Conn.QueryContext()
的所有用途.只要有意义,请使用
defer
调用这样的Close()
方法,因此即使您的代码出现 panic 或有 return
在“手动”调用之前声明。您的代码中的此类示例是
csvFile.Close()
.有return
s 之前,如果其中一个分支被执行,csvFile
不会关闭。像这样做:
csvFile, err = os.Open(file)
if err != nil {
for err != nil {
fmt.Println("Encountered error in opening file.. trying again in 10 seconds.")
time.Sleep(10 * time.Second)
csvFile, err = os.Open(file)
}
fmt.Println(err)
}
defer func() {
if err2 := csvFile.Close(); err2 != nil {
fmt.Println("Error closing csvFile:", err2
}
}()
关于Go 程序内存消耗在 Windows Server 2016 上不断增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62654218/