Merge pull request #314 from trheyi/main

[optimize] close the DB connections when reloading
This commit is contained in:
Max 2023-01-16 15:22:57 +08:00 committed by GitHub
commit 9ca79c9b70
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 30 additions and 4 deletions

View file

@ -44,6 +44,7 @@ func TestCommandStart(t *testing.T) {
service.Stop(func() {})
log.Println("服务已关闭")
}()
go func() {
os.Args = append(os.Args, "start")
main()
@ -68,9 +69,9 @@ func TestCommandStart(t *testing.T) {
}
// 等待服务启动
time.Sleep(time.Second * 2)
times := 0
for times < 20 { // 2秒超时
for times < 30 { // 2秒超时
time.Sleep(time.Second * 2)
times++
fmt.Printf("Trying(%d)...", times)
res, err := request()
@ -115,9 +116,9 @@ func TestCommandStop(t *testing.T) {
}
// 等待服务启动
time.Sleep(time.Second * 2)
times := 0
for times < 20 { // 2秒超时
for times < 30 { // 2秒超时
time.Sleep(time.Second * 2)
times++
res, err := request()
if err != nil {

View file

@ -69,6 +69,7 @@ func Stop(onComplete func()) {
select {
case <-shutdownComplete:
share.SessionStop()
share.DBClose()
onComplete()
}
}

View file

@ -2,6 +2,7 @@ package share
import (
"fmt"
"strings"
"time"
"github.com/yaoapp/kun/log"
@ -45,3 +46,26 @@ func DBConnect(dbconfig config.DBConfig) (err error) {
return err
}
// DBClose close the database connections
func DBClose() error {
messages := []string{}
capsule.Global.Connections.Range(func(key, value any) bool {
log.Trace("[DBClose] %s", key)
if conn, ok := value.(*capsule.Connection); ok {
err := conn.Close()
if err != nil {
messages = append(messages, err.Error())
}
}
return true
})
if len(messages) > 0 {
msg := fmt.Sprintf("[DBClose] %s ", strings.Join(messages, ";"))
log.Error(msg)
return fmt.Errorf(msg)
}
return nil
}