40

groupcache 使用示例

 5 years ago
source link: https://studygolang.com/articles/18554?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

    3mYzqy6.png!web

    1.png

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

    MBNNfyy.png!web

    2.png

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

    zAvYVrY.png!web

    3.png

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

    63IZjyv.png!web

    4.png


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK