| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- package busmodels
- import (
- "fmt"
- "os"
- "strings"
- "time"
- "github.com/muesli/cache2go"
- )
- /*
- 图片文件或者视频文件等媒体文件的缓存信息,
- 在视频封面截图或者图片缩略图的生成以后才会记录.
- MediaPath 是视频文件或者图片文件的唯一uuid,也就是地址索引.
- CreatedAt 记录操作时间, 用户超时不提交信息,就删除
- */
- type BusMediaCache struct {
- MediaName string `json:"mediaName" gorm:"size:128;"`
- MediaPath string `json:"mediaPath" gorm:"size:128;"`
- }
- func MediaCacheSetup() {
- cache := cache2go.Cache("MediaCache")
- // cache2go supports a few handy callbacks and loading mechanisms.
- cache.SetAboutToDeleteItemCallback(func(e *cache2go.CacheItem) {
- fmt.Println("Deleting:", e.Key(), e.Data().(*BusMediaCache).MediaPath, e.CreatedOn())
- //todo delete media source
- fmt.Println(e.LifeSpan().Seconds())
- fmt.Println(e.CreatedOn().Unix())
- fmt.Println(time.Now().Unix())
- //要区分手动删除缓存和超时删除缓存. 手动删除的话,只删除缓存,不删除本地内容, 超时删除,会删除缓存和本地数据
- if time.Now().Unix()-e.CreatedOn().Unix() >= int64(e.LifeSpan().Seconds()) {
- if _, err := os.Stat(e.Data().(*BusMediaCache).MediaPath); err != nil {
- fmt.Println(e.Data().(*BusMediaCache).MediaName + " not existed.")
- }
- if err := os.Remove(e.Data().(*BusMediaCache).MediaPath); err != nil {
- fmt.Println(e.Data().(*BusMediaCache).MediaName + " delete failed.")
- } else {
- fmt.Println(e.Data().(*BusMediaCache).MediaName + " deleted.")
- }
- coverPath := strings.Split(e.Data().(*BusMediaCache).MediaPath, ".")[0] + ".jpg"
- if err := os.Remove(coverPath); err != nil {
- fmt.Println(coverPath + " delete failed.")
- } else {
- fmt.Println(coverPath + " deleted.")
- }
- } else {
- fmt.Println("手动删除缓存.")
- }
- })
- //cache.SEt
- }
- //查询缓存是否存在.
- func (e *BusMediaCache) GetCache() error {
- //添加数据
- cache := cache2go.Cache("MediaCache")
- res, err := cache.Value(e.MediaPath)
- if err == nil {
- fmt.Println("Found value in cache:", res.Data().(*BusMediaCache).MediaName)
- } else {
- fmt.Println("Error retrieving value from cache:", err)
- return err
- }
- return nil
- }
- func (e *BusMediaCache) AddCache() (err error) {
- //添加数据
- cache := cache2go.Cache("MediaCache")
- //添加 超时时间
- cache.Add(e.MediaPath, 1*time.Minute, e)
- return nil
- }
- //delelte media cache
- func (e *BusMediaCache) DeleteCache() (err error) {
- cache := cache2go.Cache("MediaCache")
- if _, err := cache.Delete(e.MediaPath); err != nil {
- return err
- }
- fmt.Println("delete cache", e.MediaName)
- return nil
- }
- //delelte media cache
- func (e *BusMediaCache) DeleteCacheKey() (err error) {
- cache := cache2go.Cache("MediaCache")
- if _, err := cache.Delete(e.MediaPath); err != nil {
- return err
- }
- fmt.Println("delete cache", e.MediaName)
- return nil
- }
|