Feat: cache in-memory store

This commit is contained in:
HFO4
2019-12-05 17:01:14 +08:00
parent 5d50e7ed1e
commit 7375cc01f1
8 changed files with 134 additions and 26 deletions

View File

@@ -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