go使用memcache
使用文档:https://godoc.org/github.com/bradfitz/gomemcache/memcache#Client
import (
"fmt"
"github.com/bradfitz/gomemcache/memcache"
)
var Client *memcache.Client
const (
MEMCACHE_HOST = ""
MEMCACHE_PORT = ""
)
var CacheErr error
func Cache() {
dsn := fmt.Sprintf("%s:%s", MEMCACHE_HOST, MEMCACHE_PORT)
Client = memcache.New(dsn)
// 添加一个key,过期时间为100s
Client.Add(&memcache.Item{
Key: "golang",
Value: []byte("test golang memcache"),
Flags: 0,
Expiration: 100,
})
// 获取一个key
item1, CacheErr := Client.Get("golang")
if CacheErr != nil {
fmt.Println(CacheErr.Error())
} else {
fmt.Println(string(item1.Value), item1.Key)
}
// 替换一个key,替换掉上面添加的key
Client.Replace(&memcache.Item{
Key: "golang",
Value: []byte("replace golang memcache"),
Flags: 0,
Expiration: 100,
})
// 获取一个key
item2, CacheErr := Client.Get("golang")
if CacheErr != nil {
fmt.Println(CacheErr.Error())
} else {
fmt.Println(string(item2.Value), item2.Key)
}
// 删除一个key
CacheErr = Client.Delete("golang")
if CacheErr != nil {
fmt.Println(CacheErr.Error())
} else {
fmt.Println("删除成功!")
}
// 删除全部
CacheErr = Client.DeleteAll()
if CacheErr != nil {
fmt.Println(CacheErr.Error())
} else {
fmt.Println("全部删除成功!")
}
}
网友评论