Created
March 29, 2014 05:55
-
-
Save yosisa/9849327 to your computer and use it in GitHub Desktop.
groupcache で組み込み型分散キャッシュ ref: http://qiita.com/yosisa/items/4980559f328fb31c3a8d
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"github.com/codegangsta/martini" | |
"github.com/golang/groupcache" | |
"net/http" | |
"os" | |
"time" | |
) | |
func main() { | |
addr := os.Getenv("GROUPCACHE_ADDR") | |
peers := groupcache.NewHTTPPool("http://" + addr) | |
peers.Set("http://127.0.0.1:8000", "http://127.0.0.1:8001") | |
go http.ListenAndServe(addr, peers) | |
heavy := groupcache.NewGroup("heavy", 64<<20, groupcache.GetterFunc(heavyTask)) | |
m := martini.Classic() | |
m.Get("/_stats", func() []byte { | |
v, err := json.Marshal(&heavy.Stats) | |
if err != nil { | |
panic(err) | |
} | |
return v | |
}) | |
m.Get("/:key", func(params martini.Params) string { | |
var result string | |
if err := heavy.Get(nil, params["key"], groupcache.StringSink(&result)); err != nil { | |
panic(err) | |
} | |
return result | |
}) | |
m.Run() | |
} | |
func heavyTask(ctx groupcache.Context, key string, dst groupcache.Sink) error { | |
time.Sleep(400 * time.Millisecond) | |
dst.SetString("Value of " + key) | |
return nil | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ GROUPCACHE_ADDR=127.0.0.1:8000 go run main.go | |
$ GROUPCACHE_ADDR=127.0.0.1:8001 PORT=3001 go run main.go |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ curl localhost:3000/foo # 400ms | |
$ curl localhost:3001/foo # <1ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice demo.