Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[fix] 解决json配置文件在热更新时,因系统触发两次文件写入事件,第一次读取到的配置内容为空,导致json解析失败报错的问题 #3431

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions config/file/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"os"
"path/filepath"
"time"

"github.com/fsnotify/fsnotify"

Expand Down Expand Up @@ -52,6 +53,7 @@ func (w *watcher) Next() ([]*config.KeyValue, error) {
if fi.IsDir() {
path = filepath.Join(w.f.path, filepath.Base(event.Name))
}
time.Sleep(time.Millisecond)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can sleep here solve the problem?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

未添加Sleep前,每次保存配置触发的两次写事件时,第一次读取到的内容均为空。添加Sleep后,进行100次连续保存操作,每次触发的两次写事件,均能读取到文件内容。

kv, err := w.f.loadFile(path)
if err != nil {
return nil, err
Expand Down
3 changes: 3 additions & 0 deletions encoding/json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ func (codec) Marshal(v interface{}) ([]byte, error) {
}

func (codec) Unmarshal(data []byte, v interface{}) error {
if len(data) == 0 {
return nil
}
switch m := v.(type) {
case json.Unmarshaler:
return m.UnmarshalJSON(data)
Expand Down
Loading