mirror of
https://github.com/halejohn/Cloudreve.git
synced 2026-01-27 18:11:57 +08:00
Feat: cache in-memory store
This commit is contained in:
@@ -2,11 +2,11 @@ package model
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/HFO4/cloudreve/pkg/cache"
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
"github.com/jinzhu/gorm"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -42,28 +42,20 @@ type PolicyOption struct {
|
||||
RangeTransferEnabled bool `json:"range_transfer_enabled"`
|
||||
}
|
||||
|
||||
// 存储策略缓存,部分情况下需要频繁查询存储策略
|
||||
var policyCache = make(map[uint]Policy)
|
||||
var rw sync.RWMutex
|
||||
|
||||
// GetPolicyByID 用ID获取存储策略
|
||||
func GetPolicyByID(ID interface{}) (Policy, error) {
|
||||
// 尝试读取缓存
|
||||
rw.RLock()
|
||||
if policy, ok := policyCache[ID.(uint)]; ok {
|
||||
rw.RUnlock()
|
||||
return policy, nil
|
||||
cacheKey := "policy_" + strconv.Itoa(int(ID.(uint)))
|
||||
if policy, ok := cache.Store.Get(cacheKey); ok {
|
||||
return policy.(Policy), nil
|
||||
}
|
||||
rw.RUnlock()
|
||||
|
||||
var policy Policy
|
||||
result := DB.First(&policy, ID)
|
||||
|
||||
// 写入缓存
|
||||
if result.Error == nil {
|
||||
rw.Lock()
|
||||
policyCache[policy.ID] = policy
|
||||
rw.Unlock()
|
||||
_ = cache.Store.Set(cacheKey, policy)
|
||||
}
|
||||
|
||||
return policy, result.Error
|
||||
|
||||
Reference in New Issue
Block a user