go 超级萌新,求问 go-cache 的问题
目的:设置缓存,在缓存未过期时从缓存读取数据,如果读取失败,则将缓存内容写入缓存;最后将内容打印出来。
package main
import (
“fmt”
“time”
“github.com/patrickmn/go-cache”
)
func main() {
var id cateId = 20
data := id.getCache()
fmt.Println(data)
}
type cateId int
func (id cateId) getCache() string {
cacheName := “cache_20”
//cacheName := “cache_” + string(id)
c := cache.New(30*time.Second, 20*time.Second)
value, found := c.Get(cacheName)
if found {
return value.(string)
} else {
c.Set(cacheName, “testdata_20”, cache.DefaultExpiration)
return “testdata_200”
//return “testdata_” + string(id) //始终输出 testdata_
}
}
问题 1:编译后执行得到的结果始终是 testdata_200,缓存 30 秒过期,第一次执行得到 testdata_200 正常,为什么第二次执行得到的不是缓存数据 testdata_20 呢?莫非 go-cache 在程序运行结束,缓存也消失了?
问题 2://return “testdata_” + string(id) //始终输出 testdata_,而不是输出 testdata_20 ?在 windows 命令行窗口 20 是个乱码,其他终端下运行直接没有
问题 3:我这样写符合大众习惯吗?毕竟这个写法跟我以前用 PHP/Python 差别挺大的。。
PHP 为例:
$data = $this->_getCache(20);
protected _getCache(cateId)
{
$data = Cache->get(‘cacheName’);
if( !$data ){
$data = ‘一些数据’
Cache->set(‘cacheName’, $data);
}
return $data;
}
先谢谢大家!