123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255 |
- package cache
- import (
- "bytes"
- "crypto/md5"
- "encoding/gob"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "path/filepath"
- "reflect"
- "strconv"
- "time"
- )
- type FileCacheItem struct {
- Data interface{}
- Lastaccess time.Time
- Expired time.Time
- }
- var (
- FileCachePath = "cache"
- FileCacheFileSuffix = ".bin"
- FileCacheDirectoryLevel = 2
- FileCacheEmbedExpiry time.Duration
- )
- type FileCache struct {
- CachePath string
- FileSuffix string
- DirectoryLevel int
- EmbedExpiry int
- }
- func NewFileCache() Cache {
-
- return &FileCache{}
- }
- func (fc *FileCache) StartAndGC(config string) error {
- var cfg map[string]string
- json.Unmarshal([]byte(config), &cfg)
- if _, ok := cfg["CachePath"]; !ok {
- cfg["CachePath"] = FileCachePath
- }
- if _, ok := cfg["FileSuffix"]; !ok {
- cfg["FileSuffix"] = FileCacheFileSuffix
- }
- if _, ok := cfg["DirectoryLevel"]; !ok {
- cfg["DirectoryLevel"] = strconv.Itoa(FileCacheDirectoryLevel)
- }
- if _, ok := cfg["EmbedExpiry"]; !ok {
- cfg["EmbedExpiry"] = strconv.FormatInt(int64(FileCacheEmbedExpiry.Seconds()), 10)
- }
- fc.CachePath = cfg["CachePath"]
- fc.FileSuffix = cfg["FileSuffix"]
- fc.DirectoryLevel, _ = strconv.Atoi(cfg["DirectoryLevel"])
- fc.EmbedExpiry, _ = strconv.Atoi(cfg["EmbedExpiry"])
- fc.Init()
- return nil
- }
- func (fc *FileCache) Init() {
- if ok, _ := exists(fc.CachePath); !ok {
- _ = os.MkdirAll(fc.CachePath, os.ModePerm)
- }
- }
- func (fc *FileCache) getCacheFileName(key string) string {
- m := md5.New()
- io.WriteString(m, key)
- keyMd5 := hex.EncodeToString(m.Sum(nil))
- cachePath := fc.CachePath
- switch fc.DirectoryLevel {
- case 2:
- cachePath = filepath.Join(cachePath, keyMd5[0:2], keyMd5[2:4])
- case 1:
- cachePath = filepath.Join(cachePath, keyMd5[0:2])
- }
- if ok, _ := exists(cachePath); !ok {
- _ = os.MkdirAll(cachePath, os.ModePerm)
- }
- return filepath.Join(cachePath, fmt.Sprintf("%s%s", keyMd5, fc.FileSuffix))
- }
- func (fc *FileCache) Get(key string) interface{} {
- fileData, err := FileGetContents(fc.getCacheFileName(key))
- if err != nil {
- return ""
- }
- var to FileCacheItem
- GobDecode(fileData, &to)
- if to.Expired.Before(time.Now()) {
- return ""
- }
- return to.Data
- }
- func (fc *FileCache) GetMulti(keys []string) []interface{} {
- var rc []interface{}
- for _, key := range keys {
- rc = append(rc, fc.Get(key))
- }
- return rc
- }
- func (fc *FileCache) Put(key string, val interface{}, timeout time.Duration) error {
- gob.Register(val)
- item := FileCacheItem{Data: val}
- if timeout == FileCacheEmbedExpiry {
- item.Expired = time.Now().Add((86400 * 365 * 10) * time.Second)
- } else {
- item.Expired = time.Now().Add(timeout)
- }
- item.Lastaccess = time.Now()
- data, err := GobEncode(item)
- if err != nil {
- return err
- }
- return FilePutContents(fc.getCacheFileName(key), data)
- }
- func (fc *FileCache) Delete(key string) error {
- filename := fc.getCacheFileName(key)
- if ok, _ := exists(filename); ok {
- return os.Remove(filename)
- }
- return nil
- }
- func (fc *FileCache) Incr(key string) error {
- data := fc.Get(key)
- var incr int
- if reflect.TypeOf(data).Name() != "int" {
- incr = 0
- } else {
- incr = data.(int) + 1
- }
- fc.Put(key, incr, FileCacheEmbedExpiry)
- return nil
- }
- func (fc *FileCache) Decr(key string) error {
- data := fc.Get(key)
- var decr int
- if reflect.TypeOf(data).Name() != "int" || data.(int)-1 <= 0 {
- decr = 0
- } else {
- decr = data.(int) - 1
- }
- fc.Put(key, decr, FileCacheEmbedExpiry)
- return nil
- }
- func (fc *FileCache) IsExist(key string) bool {
- ret, _ := exists(fc.getCacheFileName(key))
- return ret
- }
- func (fc *FileCache) ClearAll() error {
- return nil
- }
- func exists(path string) (bool, error) {
- _, err := os.Stat(path)
- if err == nil {
- return true, nil
- }
- if os.IsNotExist(err) {
- return false, nil
- }
- return false, err
- }
- func FileGetContents(filename string) (data []byte, e error) {
- return ioutil.ReadFile(filename)
- }
- func FilePutContents(filename string, content []byte) error {
- return ioutil.WriteFile(filename, content, os.ModePerm)
- }
- func GobEncode(data interface{}) ([]byte, error) {
- buf := bytes.NewBuffer(nil)
- enc := gob.NewEncoder(buf)
- err := enc.Encode(data)
- if err != nil {
- return nil, err
- }
- return buf.Bytes(), err
- }
- func GobDecode(data []byte, to *FileCacheItem) error {
- buf := bytes.NewBuffer(data)
- dec := gob.NewDecoder(buf)
- return dec.Decode(&to)
- }
- func init() {
- Register("file", NewFileCache)
- }
|