乐趣区

关于golang:工具库系列之Golang实现的能自动回收过期值的内存缓存库

Golang 实现的能主动回收过期值的内存缓存库




English README

该库应用了红黑树和最小堆数据结构。利用最小堆堆顶是最老的值,从而疾速荡涤过期值。能够认为是一个有过期工夫的 K-V 本地内存数据库。

原理很简略:

  1. 一个 treeMap 用来保留 K-V,一个最小堆的齐全树用来荡涤过期 key
  2. 官网的 map 不会缩容,treemap 的话不会占用多余空间。
  3. 开了个定时器惰性删除过期 key,因为定时器每秒最多革除 30 个过期,可能不够实时,所以当客户端被动拿值时会进行实时删除 key,参考的 redis。

数据保留在内存中,又快又好,这个内存缓存库十分高效,不须要预调配空间。

应用

间接执行:

go get -v github.com/hunterhug/gocache

例子

参考以下办法:

type Cache interface {Set(key string, value []byte, expireTime time.Duration)
    SetInterface(key string, value interface{}, expireTime time.Duration)
    SetByExpireUnixNanosecondDateTime(key string, value []byte, expireUnixNanosecondDateTime int64)
    SetInterfaceByExpireUnixNanosecondDateTime(key string, value interface{}, expireUnixNanosecondDateTime int64)
    Delete(key string)
    Get(key string) (value []byte, expireUnixNanosecondDateTime int64, exist bool)
    GetInterface(key string) (value interface{}, expireUnixNanosecondDateTime int64, exist bool)
    GetOldestKey() (key string, expireUnixNanosecondDateTime int64, exist bool)
    Size() int
    Index(index int) (value []byte, expireUnixNanosecondDateTime int64, exist bool)
    IndexInterface(index int) (value interface{}, expireUnixNanosecondDateTime int64, exist bool)
    KeyList() []string
    ShutDown()}

设置缓存时,能够抉择应用 time.Duration 来设置过期工夫,外部转化之后的工夫是纳秒 expireUnixNanosecondDateTime

例子:

package main

import (
    "fmt"
    "github.com/hunterhug/gocache"
    "time"
)

func main() {cache := gocache.New()
    defer cache.ShutDown()

    cache.Set("a", []byte("a hi"), 2*time.Second)
    cache.Set("b", []byte("b hi"), 2*time.Second)
    cache.SetInterface("c", []byte("c hi"), 2*time.Second)

    fmt.Println(cache.Size())
    fmt.Println(cache.GetOldestKey())
    fmt.Println(cache.KeyList())
    fmt.Println(cache.Get("a"))
    fmt.Println(cache.GetInterface("c"))

    time.Sleep(2 * time.Second)
    fmt.Println(cache.Get("a"))
}

License

Copyright [2019-2021] [github.com/hunterhug]

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.
退出移动版