fix data race

This commit is contained in:
yusing
2025-02-24 19:24:46 +08:00
parent 135c79d2ad
commit 0d388a396c
8 changed files with 29 additions and 20 deletions

View File

@@ -14,7 +14,9 @@ type HealthCheckConfig struct {
Timeout time.Duration `json:"timeout" validate:"omitempty,min=1s"`
}
var DefaultHealthConfig = &HealthCheckConfig{
Interval: common.HealthCheckIntervalDefault,
Timeout: common.HealthCheckTimeoutDefault,
func DefaultHealthConfig() *HealthCheckConfig {
return &HealthCheckConfig{
Interval: common.HealthCheckIntervalDefault,
Timeout: common.HealthCheckTimeoutDefault,
}
}

View File

@@ -25,7 +25,7 @@ type (
url atomic.Value[*types.URL]
status atomic.Value[health.Status]
lastResult *health.HealthCheckResult
lastResult atomic.Value[*health.HealthCheckResult]
checkHealth HealthCheckFunc
startTime time.Time
@@ -139,10 +139,11 @@ func (mon *monitor) Uptime() time.Duration {
// Latency implements HealthMonitor.
func (mon *monitor) Latency() time.Duration {
if mon.lastResult == nil {
res := mon.lastResult.Load()
if res == nil {
return 0
}
return mon.lastResult.Latency
return res.Latency
}
// Name implements HealthMonitor.
@@ -158,7 +159,7 @@ func (mon *monitor) String() string {
// MarshalJSON implements json.Marshaler of HealthMonitor.
func (mon *monitor) MarshalJSON() ([]byte, error) {
res := mon.lastResult
res := mon.lastResult.Load()
if res == nil {
res = &health.HealthCheckResult{
Healthy: true,
@@ -190,7 +191,7 @@ func (mon *monitor) checkUpdateHealth() error {
return nil
}
mon.lastResult = result
mon.lastResult.Store(result)
var status health.Status
if result.Healthy {
status = health.StatusHealthy