fix(id): 使用sync.Once与sync.RWMutex消除getLocalIP并发数据竞争
Some checks are pending
Security Checks / security (push) Waiting to run
Some checks are pending
Security Checks / security (push) Waiting to run
This commit is contained in:
parent
9a6751ef2d
commit
44111ae659
@ -7,32 +7,38 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
var ip_instance string
|
var (
|
||||||
|
ipInstance string
|
||||||
|
ipOnce sync.Once
|
||||||
|
ipMu sync.RWMutex
|
||||||
|
)
|
||||||
|
|
||||||
func getLocalIP() string {
|
func getLocalIP() string {
|
||||||
if ip_instance != "" {
|
ipOnce.Do(func() {
|
||||||
return ip_instance
|
ip := "127.0.0.1"
|
||||||
}
|
addrs, err := net.InterfaceAddrs()
|
||||||
|
if err == nil {
|
||||||
ip := "127.0.0.1"
|
for _, a := range addrs {
|
||||||
addrs, err := net.InterfaceAddrs()
|
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
|
||||||
if err != nil {
|
if ipnet.IP.To4() != nil {
|
||||||
ip_instance = ip
|
ip = ipnet.IP.String()
|
||||||
return ip
|
break
|
||||||
}
|
}
|
||||||
for _, a := range addrs {
|
}
|
||||||
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
|
|
||||||
if ipnet.IP.To4() != nil {
|
|
||||||
ip = ipnet.IP.String()
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
ipMu.Lock()
|
||||||
ip_instance = ip
|
ipInstance = ip
|
||||||
return ip
|
ipMu.Unlock()
|
||||||
|
})
|
||||||
|
|
||||||
|
ipMu.RLock()
|
||||||
|
defer ipMu.RUnlock()
|
||||||
|
return ipInstance
|
||||||
}
|
}
|
||||||
|
|
||||||
func GenLogID() string {
|
func GenLogID() string {
|
||||||
|
|||||||
31
backend/utils/id/logid_test.go
Normal file
31
backend/utils/id/logid_test.go
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
package id
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetLocalIPConcurrent(t *testing.T) {
|
||||||
|
const goroutines = 50
|
||||||
|
const iterations = 100
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
wg.Add(goroutines)
|
||||||
|
|
||||||
|
for i := 0; i < goroutines; i++ {
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
for j := 0; j < iterations; j++ {
|
||||||
|
ip := getLocalIP()
|
||||||
|
if ip == "" {
|
||||||
|
t.Errorf("getLocalIP returned empty")
|
||||||
|
}
|
||||||
|
logID := GenLogID()
|
||||||
|
if logID == "" {
|
||||||
|
t.Errorf("GenLogID returned empty")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user