Files
bulma/atomic_config.go

37 lines
1.0 KiB
Go

// bulma/atomic_config.go
package main
import (
"fmt"
"sync/atomic"
"time"
)
// Config 配置结构体(实际项目中可扩展)
type Config struct {
APIURL string // API地址
TimeoutMS int // 超时时间(毫秒)
}
func main() {
var current atomic.Value
// 初始化配置:首次存储需指定类型(推荐存储指针,避免值拷贝)
current.Store(&Config{APIURL: "v1.example.com", TimeoutMS: 1000})
// 后台goroutine:模拟配置热更新(实际场景可从配置中心拉取)
go func() {
time.Sleep(100 * time.Millisecond)
newConf := &Config{APIURL: "v2.example.com", TimeoutMS: 2000}
current.Store(newConf) // 原子替换整个配置
fmt.Println("🔄 配置已热更新!")
}()
// 业务goroutine:持续读取配置(无锁,高效)
for i := 0; i < 5; i++ {
// 类型断言:需与存储类型一致(此处为*Config),否则panic
cfg := current.Load().(*Config)
fmt.Printf("[%d] 当前API: %s, 超时: %dms\n", i, cfg.APIURL, cfg.TimeoutMS)
time.Sleep(50 * time.Millisecond)
}
}