花了一天时间看了下实验楼的cache组件,使用golang编写的,收获还是蛮多的,缓存组件的设计其实挺简单的,主要思路或者设计点如下:
- 全局struct对象:用来做缓存(基于该struct实现增删改查基本操作)
- 定时gc功能(其实就是定时删除struct对象中过期的缓存对):刚好用上golang的ticker外加channel控制实现
- 支持缓存写文件及从文件读缓存:其实就是将这里的key-value数据通过gob模块进行一次编解码操作
- 并发读写:上锁(golang支持读写锁,一般使用时在被操作的struct对象里面声明相应的锁,即sync.RWMutex,操作之前先上锁,之后解锁即可)
其实大概就是这么多,下面来分解下:
1、cache组件
要保存数据到缓存(即内存中),先要设计数据结构,cache一般都有过期时间,抽象的struct如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
type Item
struct
{
Object
interface
{}
//数据项
Expiration int64
//数据项过期时间(0永不过期)
}
type Cache
struct
{
defaultExpiration time.Duration
//如果数据项没有指定过期时使用
items map[
string
]Item
mu sync.RWMutex
//读写锁
gcInterval time.Duration
//gc周期
stopGc chan
bool
//停止gc管道标识
}
|
1
2
3
4
5
6
|
func (item Item) IsExpired()
bool
{
if
item.Expiration == 0 {
return
false
}
return
time.Now().UnixNano() > item.Expiration
//如果当前时间超则过期
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//循环gc
func (c *Cache) gcLoop() {
ticker := time.NewTicker(c.gcInterval)
//初始化一个定时器
for
{
select
{
case
<-ticker.C:
c.DeleteExpired()
case
<-c.stopGc:
ticker.Stop()
return
}
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
//将缓存数据写入io.Writer中
func (c *Cache) Save(w io.Writer) (err error) {
enc := gob.NewEncoder(w)
defer func() {
if
x := recover(); x != nil {
err = fmt.Errorf(
"Error Registering item types with gob library"
)
}
}()
c.mu.RLock()
defer c.mu.RUnlock()
for
_,v := range c.items {
gob.Register(v.Object)
}
err = enc.Encode(&c.items)
return
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//从io.Reader读取
func (c *Cache) Load(r io.Reader) error {
dec := gob.NewDecoder(r)
items := make(map[
string
]Item,0)
err := dec.Decode(&items)
if
err != nil {
return
err
}
c.mu.Lock()
defer c.mu.Unlock()
for
k,v := range items {
obj,ok := c.items[k]
if
!ok || obj.IsExpired() {
c.items[k] = v
}
}
return
nil
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
package main
import (
"cache"
"fmt"
"time"
)
func main() {
defaultExpiration,_ := time.ParseDuration(
"0.5h"
)
gcInterval,_ := time.ParseDuration(
"3s"
)
c := cache.NewCache(defaultExpiration,gcInterval)
expiration,_ := time.ParseDuration(
"2s"
)
k1 :=
"hello world!"
c.Set(
"k1"
,k1,expiration)
if
v,found := c.Get(
"k1"
); found {
fmt.Println(
"found k1:"
,v)
}
else
{
fmt.Println(
"not found k1"
)
}
err := c.SaveToFile(
"./items.txt"
)
if
err != nil {
fmt.Println(err)
}
err = c.LoadFromFile(
"./items.txt"
)
if
err != nil {
fmt.Println(err)
}
s,_ := time.ParseDuration(
"4s"
)
time.Sleep(s)
if
v,found := c.Get(
"k1"
); found {
fmt.Println(
"found k1:"
,v)
}
else
{
fmt.Println(
"not found k1"
)
}
}
|