add time.Duration parameter support for gfcache

This commit is contained in:
John
2019-07-09 13:19:28 +08:00
parent 1f315c5b8d
commit 9ac3841342

View File

@ -8,6 +8,8 @@
package gfcache
import (
"time"
"github.com/gogf/gf/g/internal/cmdenv"
"github.com/gogf/gf/g/os/gcache"
"github.com/gogf/gf/g/os/gfile"
@ -27,18 +29,18 @@ var (
// GetContents returns string content of given file by <path> from cache.
// If there's no content in the cache, it will read it from disk file specified by <path>.
// The parameter <expire> specifies the caching time for this file content in seconds.
func GetContents(path string, expire ...int) string {
return string(GetBinContents(path, expire...))
func GetContents(path string, duration ...interface{}) string {
return string(GetBinContents(path, duration...))
}
// GetBinContents returns []byte content of given file by <path> from cache.
// If there's no content in the cache, it will read it from disk file specified by <path>.
// The parameter <expire> specifies the caching time for this file content in seconds.
func GetBinContents(path string, expire ...int) []byte {
func GetBinContents(path string, duration ...interface{}) []byte {
k := cacheKey(path)
e := cacheExpire
if len(expire) > 0 {
e = expire[0]
if len(duration) > 0 {
e = getSecondExpire(duration[0])
}
r := gcache.GetOrSetFuncLock(k, func() interface{} {
b := gfile.GetBinContents(path)
@ -58,7 +60,18 @@ func GetBinContents(path string, expire ...int) []byte {
return nil
}
// 生成缓存键名
// getSecondExpire converts parameter <duration> to int type in seconds.
//
// Note that there's some performance cost in type assertion here, but it's valuable.
func getSecondExpire(duration interface{}) int {
if d, ok := duration.(time.Duration); ok {
return int(d.Nanoseconds() / 1000000000)
} else {
return duration.(int)
}
}
// cacheKey produces the cache key for gcache.
func cacheKey(path string) string {
return "gf.gfcache:" + path
}