美文网首页Golang
groupcache 使用示例

groupcache 使用示例

作者: Linrundong | 来源:发表于2019-02-28 10:53 被阅读0次

一个缓存系统,memcached的golang版本,这里先了解一下使用方式

使用示例

  • groupcache由于是框架,需要导入在编写业务代码才能运作
  • 缓存方式可自定义:db,文件等
type TblCache struct {
    Id   int
    Key string
    Value  string
}

func main() {
    //定义节点数量以及地址
    peers_addrs := []string{"http://127.0.0.1:8001", "http://127.0.0.1:8002"}
    db, _ := sql.Open("sqlite3", "./console.db")

    if len(os.Args) != 2 {
        fmt.Println("\r\n Usage local_addr \t\n local_addr must in(127.0.0.1:8001,127.0.0.1:8002)\r\n")
        os.Exit(1)
    }
    local_addr := os.Args[1]
    peers := groupcache.NewHTTPPool("http://" + local_addr)
    peers.Set(peers_addrs...)

    // 获取group对象
    image_cache := groupcache.NewGroup("testGroup", 8<<30,
    // 自定义数据获取来源
    groupcache.GetterFunc(
        func(ctx groupcache.Context, key string, dest groupcache.Sink) error {
            rows, _ := db.Query("SELECT key, value FROM tbl_cache_map where key = ?", key)
            for rows.Next(){
                p := new(TblCache)
                err := rows.Scan(&p.Key, &p.Value)
                if err != nil {
                    fmt.Println(err)
                }
                fmt.Printf("get %s of value from tbl_cache_map\n",key)
                dest.SetString("tbl_cache_map.value : " + p.Value)
            }
            return nil
        }))

    // 定义返回方式
    http.HandleFunc("/get", func(rw http.ResponseWriter, r *http.Request) {
        var data []byte
        k := r.URL.Query().Get("key")
        fmt.Printf("user get %s of value from groupcache\n", k)
        image_cache.Get(nil, k, groupcache.AllocatingByteSliceSink(&data))
        rw.Write([]byte(data))
    })

    log.Fatal(http.ListenAndServe(local_addr, nil))
}
  • groupcache.NewGroup() 获取group对象
  • groupcache.GetterFunc() 定义数据缓存方式
  • http.HandleFunc() 定义返回方式

缓存数据库数据

  • 创建一张tbl_cache_map表格用于测试</br>


    1.png
  • 先启动两个节点
TestProject.exe 127.0.0.1:8001
TestProject.exe 127.0.0.1:8002
  • 通过url获取key=3在tbl_cache_map中的value值</br>


    2.png
  • 第一次获取时因为缓存中无key=3的value数据,所以会根据自定义GetterFunc()从数据库中读取</br>


    3.png
  • 第二次获取时存在key=3的value缓存,所以直接从groupcache缓存中读取</br>


    4.png

相关文章

网友评论

    本文标题:groupcache 使用示例

    本文链接:https://www.haomeiwen.com/subject/hnfhuqtx.html