golang开发缓存组件

来源:互联网 发布:百灵鸟播音软件下载 编辑:程序博客网 时间:2024/05/29 16:09


花了一天时间看了下实验楼的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            chanbool     //停止gc管道标识
}

其中,Cache struct为全局缓存对象,缓存的key-value类型为Item,其中包含Object类型、Expiration类型,Object类型设计为interface{}就是为了可以缓存任意数据。

2、过期处理

下面是判断item中的某项是否过期:

?
1
2
3
4
5
6
func (item Item) IsExpired()bool {
    ifitem.Expiration == 0 {
        returnfalse
    }
    returntime.Now().UnixNano() > item.Expiration //如果当前时间超则过期
}

3、定时gc

想要实现定时功能,要用到golang的time包,使用NewTicker声明一个ticker类型,再使用for循环读取ticker.C数据,循环一次则取一次数据,进行一次DeleteExpired操作,Cache中的stopGc用于结束ticker,这样整个gcLoop()便会停止,使用select监听通道数据分别处理如下:

?
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
        }
    }
}

4、缓存写文件及从文件读缓存

这里要使用到golang自带gob包,gob主要用于诸如远程调用等过程的参数编解码,相比json传输而言,大数据量下效率明显占优。gob的使用一般流程是:声明一个Encoder/Decoder、然后调用Encode/Decode方法直接进行编解码,这里Decode方法一定要传指针类型,Encode方法比较任意,指针or值类型都可以,gob支持的数据类型有限,struct、slice、map这些都支持,channel和func类型不支持。编解码双方要保持“数据一致性”,比如一个struct,双方相同的的字段其类型必须一致,缺失的字段将会直接被忽略,这里还要注意字段小写是不会被gob处理的,另外还要注意一点:gob操作的数据类型包含interface{}时,必须对interface{}所表示的实际类型进行一次register方可,以下是编解码的一个应用:

?
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() {
        ifx := 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)
    iferr != nil {
        returnerr
    }
    c.mu.Lock()
    defer c.mu.Unlock()
    fork, v := range items {
        obj, ok := c.items[k]
        if!ok || obj.IsExpired() {
            c.items[k] = v
        }
    }
    returnnil
}

5、测试

其实整体实现就是对Cache struct的crud操作,就不多记录了,测试下:

?
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)
 
    ifv, found := c.Get("k1"); found {
        fmt.Println("found k1:", v)
    }else {
        fmt.Println("not found k1")
    }
 
    err := c.SaveToFile("./items.txt")
    iferr != nil {
        fmt.Println(err)
    }
    err = c.LoadFromFile("./items.txt")
    iferr != nil {
        fmt.Println(err)
    }
 
    s, _ := time.ParseDuration("4s")
    time.Sleep(s)
    ifv, found := c.Get("k1"); found {
        fmt.Println("found k1:", v)
    }else {
        fmt.Println("not found k1")
    }
 
}

输出结果如下:

image

这里对k1设置2s的过期时间,time.Sleep等待4s之后再去获取缓存的k1数据,这时已经为空。

至此,over。。。

0 0
原创粉丝点击