cache.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package cache
  2. import (
  3. "errors"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "sync"
  8. )
  9. var cacheLock = sync.Mutex{}
  10. var listCachePath []string
  11. type FileCache struct {
  12. dirName string
  13. size int
  14. }
  15. func NewFileCache(dirName string, size int) *FileCache {
  16. listCachePath = []string{}
  17. return &FileCache{
  18. dirName: dirName,
  19. size: size,
  20. }
  21. }
  22. func (f *FileCache) SetData(key string, data []byte) error {
  23. if len(key) < 2 {
  24. return errors.New("key长度最少2")
  25. }
  26. cacheLock.Lock()
  27. defer cacheLock.Unlock()
  28. //提取目录
  29. subDir := key[0:2]
  30. keyFilePath := f.dirName + "/" + subDir + "/" + key
  31. //判断是否超过size了
  32. if len(listCachePath) >= f.size && f.size > 0 {
  33. //获取第一个
  34. removePath := listCachePath[0]
  35. _ = os.Remove(removePath)
  36. //删除第一个
  37. listCachePath = listCachePath[1:]
  38. }
  39. listCachePath = append(listCachePath, keyFilePath)
  40. _ = os.Mkdir(f.dirName+"/"+subDir, os.ModePerm)
  41. err := ioutil.WriteFile(keyFilePath, data, 0666)
  42. return err
  43. }
  44. func (f *FileCache) GetData(key string) ([]byte, error) {
  45. if len(key) < 2 {
  46. return nil, errors.New("key长度最少2")
  47. }
  48. cacheLock.Lock()
  49. defer cacheLock.Unlock()
  50. subDir := key[0:2]
  51. keyFilePath := f.dirName + "/" + subDir + "/" + key
  52. return ioutil.ReadFile(keyFilePath)
  53. }
  54. func (f *FileCache) ClearCache() error {
  55. cacheLock.Lock()
  56. defer cacheLock.Unlock()
  57. d, err := os.Open(f.dirName)
  58. if err != nil {
  59. return err
  60. }
  61. defer d.Close()
  62. names, err := d.Readdirnames(-1)
  63. if err != nil {
  64. return err
  65. }
  66. for _, name := range names {
  67. err = os.RemoveAll(filepath.Join(f.dirName, name))
  68. if err != nil {
  69. return err
  70. }
  71. }
  72. return nil
  73. }