NewCache new cache instance
(c *CacheConf)
| 96 | |
| 97 | // NewCache new cache instance |
| 98 | func NewCache(c *CacheConf) (cache.Cache, func(), error) { |
| 99 | var pluginCache plugin.Cache |
| 100 | _ = plugin.CallCache(func(fn plugin.Cache) error { |
| 101 | pluginCache = fn |
| 102 | return nil |
| 103 | }) |
| 104 | if pluginCache != nil { |
| 105 | return pluginCache, func() {}, nil |
| 106 | } |
| 107 | |
| 108 | // TODO What cache type should be initialized according to the configuration file |
| 109 | memCache := memory.NewCache() |
| 110 | |
| 111 | if len(c.FilePath) > 0 { |
| 112 | cacheFileDir := filepath.Dir(c.FilePath) |
| 113 | log.Debugf("try to create cache directory %s", cacheFileDir) |
| 114 | err := dir.CreateDirIfNotExist(cacheFileDir) |
| 115 | if err != nil { |
| 116 | log.Errorf("create cache dir failed: %s", err) |
| 117 | } |
| 118 | log.Infof("try to load cache file from %s", c.FilePath) |
| 119 | if err := memory.Load(memCache, c.FilePath); err != nil { |
| 120 | log.Warn(err) |
| 121 | } |
| 122 | go func() { |
| 123 | ticker := time.Tick(time.Minute) |
| 124 | for range ticker { |
| 125 | if err := memory.Save(memCache, c.FilePath); err != nil { |
| 126 | log.Warn(err) |
| 127 | } |
| 128 | } |
| 129 | }() |
| 130 | } |
| 131 | cleanup := func() { |
| 132 | log.Infof("try to save cache file to %s", c.FilePath) |
| 133 | if err := memory.Save(memCache, c.FilePath); err != nil { |
| 134 | log.Warn(err) |
| 135 | } |
| 136 | } |
| 137 | return memCache, cleanup, nil |
| 138 | } |