groupcache 使用示例

栏目: 数据库 · 发布时间: 6年前

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

一个缓存系统,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>

    groupcache 使用示例

    1.png

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

    groupcache 使用示例

    2.png

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

    groupcache 使用示例

    3.png

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

    groupcache 使用示例

    4.png


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pro HTML5 and CSS3 Design Patterns

Pro HTML5 and CSS3 Design Patterns

Michael Bowers / Apress / 2011-11-15 / GBP 35.50

Pro HTML5 and CSS3 Design Patterns is a reference book and a cookbook on how to style web pages using CSS3 and HTML5. It contains 350 ready--to--use patterns (CSS3 and HTML5 code snippets) that you ca......一起来看看 《Pro HTML5 and CSS3 Design Patterns》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具