1.go开源groupcache项目——groupcache介绍

来源:互联网 发布:25t88ht总线数据 编辑:程序博客网 时间:2024/06/08 13:03

1.go开源groupcache项目——groupcache介绍

代码下载地址如下:

https://github.com/golang/groupcache

目标是在很多场景下替换memcached。

1     memcached

Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储键/值对的hashmap。其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信。

2     GROUPCACHE简单介绍

groupcache 是使用 Go 语言编写的缓存及缓存过滤库,作为 memcached 许多场景下的替代版本。

2.1     与memcached差异

首先,groupcache 与 memcached 的相似之处:通过 key 分片,并且通过 key 来查询响应的 peer。

其次,groupcache 与 memcached 的不同之处:

1. 不需要对服务器进行单独的设置,这将大幅度减少部署和配置的工作量。groupcache 既是客户端库也是服务器库,并连接到自己的 peer 上。

2. 具有缓存过滤机制。众所周知,在 memcached 出现“Sorry,cache miss(缓存丢失)”时,经常会因为不受控制用户数量的请求而导致数据库(或者其它组件)产生“惊群效应(thundering herd)”;groupcache 会协调缓存填充,只会将重复调用中的一个放于缓存,而处理结果将发送给所有相同的调用者。

3. 不支持多个版本的值。如果“foo”键对应的值是“bar”,那么键“foo”的值永远都是“bar”。这里既没有缓存的有效期,也没有明确的缓存回收机制,因此同样也没有CAS 或者 Increment/Decrement。

4. 基于上一点的改变,groupcache 就具备了自动备份“超热”项进行多重处理,这就避免了 memcached 中对某些键值过量访问而造成所在机器 CPU 或者 NIC 过载。

跟memcached 差异最大的地方在于「没有更改与删除的功能」,一旦写进去后就不会变动。在放弃update/delete 的特性后,换来的是:

l  Cluster 的能力。

l  处理热点的能力。

以往在memcached server 之间是没有交集的,在groupcache 则是cluster 起来。另外以前在memcached 会因为同时存取同一个key 而造成single CPU overloading 的问题,在groupcache 则透过auto-mirror 机制解决。

3     测试

需要下载:go getgithub.com/golang/protobuf/proto

3.1     代码

packagemain
 
import(
    "fmt"
    "log"
    "net/http"
    "os"
    "strings"
    groupcache"github.com/golang/groupcache"
)
 
funcmain(){
    //Usage:./test_groupcacheport
    me:=":"+os.Args[1]
    peers:=groupcache.NewHTTPPool("http://localhost"+me)
    peers.Set("http://localhost:8081","http://localhost:8082","http://localhost:8083")
    helloworld:=groupcache.NewGroup("helloworld",1024*1024*1024*16,groupcache.GetterFunc(
        func(ctxgroupcache.Context,keystring,destgroupcache.Sink)error{
            log.Println(me)
            dest.SetString(me)
            returnnil
        }))
    fmt.Println("GroupName:",helloworld.Name())
    http.HandleFunc("/xbox/",func(whttp.ResponseWriter,r*http.Request){
        parts:=strings.SplitN(r.URL.Path[len("/xbox/"):],"/",1)
        iflen(parts)!=1{
            http.Error(w,"BadRequest",http.StatusBadRequest)
            return
        }
        vardata[]byte
        helloworld.Get(nil,parts[0],groupcache.AllocatingByteSliceSink(&data))
        w.Write(data)
        log.Println("Gets:",helloworld.Stats.Gets.String())
        log.Println("Load:",helloworld.Stats.Loads.String())
        log.Println("LocalLoad:",helloworld.Stats.LocalLoads.String())
        log.Println("PeerError:",helloworld.Stats.PeerErrors.String())
        log.Println("PeerLoad:",helloworld.Stats.PeerLoads.String())
    })
    http.ListenAndServe(me,nil)
}

3.2     执行如下

需要加入参数

./test.exe 1989

输入一个端口号启动运行。

0 0
原创粉丝点击