1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-24 02:40:55 +00:00
Beego/client/cache/memory.go

271 lines
6.0 KiB
Go
Raw Normal View History

2020-07-22 14:50:08 +00:00
// Copyright 2014 beego Author. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cache
import (
2020-10-04 14:11:28 +00:00
"context"
2020-07-22 14:50:08 +00:00
"encoding/json"
"errors"
2020-11-17 12:53:33 +00:00
"fmt"
"strings"
2020-07-22 14:50:08 +00:00
"sync"
"time"
)
var (
2020-08-05 16:56:11 +00:00
// Timer for how often to recycle the expired cache items in memory (in seconds)
2020-07-22 14:50:08 +00:00
DefaultEvery = 60 // 1 minute
)
2020-08-05 16:44:39 +00:00
// MemoryItem stores memory cache item.
2020-07-22 14:50:08 +00:00
type MemoryItem struct {
val interface{}
createdTime time.Time
lifespan time.Duration
}
func (mi *MemoryItem) isExpire() bool {
// 0 means forever
if mi.lifespan == 0 {
return false
}
return time.Now().Sub(mi.createdTime) > mi.lifespan
}
2020-08-05 16:44:39 +00:00
// MemoryCache is a memory cache adapter.
// Contains a RW locker for safe map storage.
2020-07-22 14:50:08 +00:00
type MemoryCache struct {
sync.RWMutex
dur time.Duration
items map[string]*MemoryItem
Every int // run an expiration check Every clock time
}
// NewMemoryCache returns a new MemoryCache.
func NewMemoryCache() Cache {
cache := MemoryCache{items: make(map[string]*MemoryItem)}
return &cache
}
2020-08-05 16:44:39 +00:00
// Get returns cache from memory.
// If non-existent or expired, return nil.
2020-10-04 14:11:28 +00:00
func (bc *MemoryCache) Get(ctx context.Context, key string) (interface{}, error) {
2020-07-22 14:50:08 +00:00
bc.RLock()
defer bc.RUnlock()
2020-10-04 14:11:28 +00:00
if itm, ok := bc.items[key]; ok {
2020-07-22 14:50:08 +00:00
if itm.isExpire() {
2020-10-04 14:11:28 +00:00
return nil, errors.New("the key is expired")
2020-07-22 14:50:08 +00:00
}
2020-10-04 14:11:28 +00:00
return itm.val, nil
2020-07-22 14:50:08 +00:00
}
2020-11-17 12:53:33 +00:00
return nil, errors.New("the key isn't exist")
2020-07-22 14:50:08 +00:00
}
// GetMulti gets caches from memory.
2020-08-05 16:44:39 +00:00
// If non-existent or expired, return nil.
2020-10-04 14:11:28 +00:00
func (bc *MemoryCache) GetMulti(ctx context.Context, keys []string) ([]interface{}, error) {
2020-11-17 12:53:33 +00:00
rc := make([]interface{}, len(keys))
keysErr := make([]string, 0)
for i, ki := range keys {
val, err := bc.Get(context.Background(), ki)
2020-10-04 14:11:28 +00:00
if err != nil {
2020-11-17 12:53:33 +00:00
keysErr = append(keysErr, fmt.Sprintf("key [%s] error: %s", ki, err.Error()))
continue
2020-10-04 14:11:28 +00:00
}
2020-11-17 12:53:33 +00:00
rc[i] = val
}
if len(keysErr) == 0 {
return rc, nil
2020-07-22 14:50:08 +00:00
}
2020-11-17 12:53:33 +00:00
return rc, errors.New(strings.Join(keysErr, "; "))
2020-07-22 14:50:08 +00:00
}
2020-08-05 16:44:39 +00:00
// Put puts cache into memory.
2020-08-05 16:56:11 +00:00
// If lifespan is 0, it will never overwrite this value unless restarted
2020-10-04 14:11:28 +00:00
func (bc *MemoryCache) Put(ctx context.Context, key string, val interface{}, timeout time.Duration) error {
2020-07-22 14:50:08 +00:00
bc.Lock()
defer bc.Unlock()
2020-10-04 14:11:28 +00:00
bc.items[key] = &MemoryItem{
val: val,
2020-07-22 14:50:08 +00:00
createdTime: time.Now(),
2020-10-04 14:11:28 +00:00
lifespan: timeout,
2020-07-22 14:50:08 +00:00
}
return nil
}
// Delete cache in memory.
2020-10-04 14:11:28 +00:00
func (bc *MemoryCache) Delete(ctx context.Context, key string) error {
2020-07-22 14:50:08 +00:00
bc.Lock()
defer bc.Unlock()
2020-10-04 14:11:28 +00:00
if _, ok := bc.items[key]; !ok {
2020-07-22 14:50:08 +00:00
return errors.New("key not exist")
}
2020-10-04 14:11:28 +00:00
delete(bc.items, key)
if _, ok := bc.items[key]; ok {
2020-07-22 14:50:08 +00:00
return errors.New("delete key error")
}
return nil
}
2020-08-05 16:44:39 +00:00
// Incr increases cache counter in memory.
// Supports int,int32,int64,uint,uint32,uint64.
2020-10-04 14:11:28 +00:00
func (bc *MemoryCache) Incr(ctx context.Context, key string) error {
2020-07-22 14:50:08 +00:00
bc.Lock()
defer bc.Unlock()
itm, ok := bc.items[key]
if !ok {
return errors.New("key not exist")
}
switch val := itm.val.(type) {
case int:
itm.val = val + 1
case int32:
itm.val = val + 1
case int64:
itm.val = val + 1
case uint:
itm.val = val + 1
case uint32:
itm.val = val + 1
case uint64:
itm.val = val + 1
default:
return errors.New("item val is not (u)int (u)int32 (u)int64")
}
return nil
}
2020-08-05 16:44:39 +00:00
// Decr decreases counter in memory.
2020-10-04 14:11:28 +00:00
func (bc *MemoryCache) Decr(ctx context.Context, key string) error {
2020-07-22 14:50:08 +00:00
bc.Lock()
defer bc.Unlock()
itm, ok := bc.items[key]
if !ok {
return errors.New("key not exist")
}
switch val := itm.val.(type) {
case int:
itm.val = val - 1
case int64:
itm.val = val - 1
case int32:
itm.val = val - 1
case uint:
if val > 0 {
itm.val = val - 1
} else {
return errors.New("item val is less than 0")
}
case uint32:
if val > 0 {
itm.val = val - 1
} else {
return errors.New("item val is less than 0")
}
case uint64:
if val > 0 {
itm.val = val - 1
} else {
return errors.New("item val is less than 0")
}
default:
return errors.New("item val is not int int64 int32")
}
return nil
}
2020-08-05 16:44:39 +00:00
// IsExist checks if cache exists in memory.
2020-10-04 14:11:28 +00:00
func (bc *MemoryCache) IsExist(ctx context.Context, key string) (bool, error) {
2020-07-22 14:50:08 +00:00
bc.RLock()
defer bc.RUnlock()
2020-10-04 14:11:28 +00:00
if v, ok := bc.items[key]; ok {
return !v.isExpire(), nil
2020-07-22 14:50:08 +00:00
}
2020-10-04 14:11:28 +00:00
return false, nil
2020-07-22 14:50:08 +00:00
}
2020-08-05 16:44:39 +00:00
// ClearAll deletes all cache in memory.
2020-10-04 14:11:28 +00:00
func (bc *MemoryCache) ClearAll(context.Context) error {
2020-07-22 14:50:08 +00:00
bc.Lock()
defer bc.Unlock()
bc.items = make(map[string]*MemoryItem)
return nil
}
2020-08-05 16:44:39 +00:00
// StartAndGC starts memory cache. Checks expiration in every clock time.
2020-07-22 14:50:08 +00:00
func (bc *MemoryCache) StartAndGC(config string) error {
var cf map[string]int
json.Unmarshal([]byte(config), &cf)
if _, ok := cf["interval"]; !ok {
cf = make(map[string]int)
cf["interval"] = DefaultEvery
}
dur := time.Duration(cf["interval"]) * time.Second
bc.Every = cf["interval"]
bc.dur = dur
go bc.vacuum()
return nil
}
// check expiration.
func (bc *MemoryCache) vacuum() {
bc.RLock()
every := bc.Every
bc.RUnlock()
if every < 1 {
return
}
for {
<-time.After(bc.dur)
bc.RLock()
if bc.items == nil {
bc.RUnlock()
return
}
bc.RUnlock()
if keys := bc.expiredKeys(); len(keys) != 0 {
bc.clearItems(keys)
}
}
}
2020-08-05 16:44:39 +00:00
// expiredKeys returns keys list which are expired.
2020-07-22 14:50:08 +00:00
func (bc *MemoryCache) expiredKeys() (keys []string) {
bc.RLock()
defer bc.RUnlock()
for key, itm := range bc.items {
if itm.isExpire() {
keys = append(keys, key)
}
}
return
}
2020-08-05 16:44:39 +00:00
// ClearItems removes all items who's key is in keys
2020-07-22 14:50:08 +00:00
func (bc *MemoryCache) clearItems(keys []string) {
bc.Lock()
defer bc.Unlock()
for _, key := range keys {
delete(bc.items, key)
}
}
func init() {
Register("memory", NewMemoryCache)
}