@@ -0,0 +1,56 @@
|
||||
package configser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
configInfoPath = "/api/app/config/info"
|
||||
configInfoCacheTTL = 60 * time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
configMu sync.Mutex
|
||||
configCache *AppConfigVM
|
||||
configAt time.Time
|
||||
)
|
||||
|
||||
// FetchConfigInfo 拉取 APP 公共配置。
|
||||
func FetchConfigInfo(c *gin.Context) (*ConfigInfoResp, error) {
|
||||
var env APIEnvelope[ConfigInfoResp]
|
||||
if err := upstream.GetPublicJSON(c, configInfoPath, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("config info code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
// FetchAppConfigVMOrEmpty 带短缓存;刷新失败时优先返回最近一次成功配置。
|
||||
func FetchAppConfigVMOrEmpty(c *gin.Context) AppConfigVM {
|
||||
configMu.Lock()
|
||||
defer configMu.Unlock()
|
||||
if configCache != nil && time.Since(configAt) < configInfoCacheTTL {
|
||||
return *configCache
|
||||
}
|
||||
|
||||
info, err := FetchConfigInfo(c)
|
||||
if err != nil {
|
||||
log.Error("fetch app config info failed", log.E(err))
|
||||
if configCache != nil {
|
||||
return *configCache
|
||||
}
|
||||
return ApplyTrackerFallback(AppConfigVM{})
|
||||
}
|
||||
vm := ApplyTrackerFallback(BuildAppConfigVM(info))
|
||||
configCache = &vm
|
||||
configAt = time.Now()
|
||||
return vm
|
||||
}
|
||||
Reference in New Issue
Block a user