內(nèi)存不夠用還要速度快,終于找到可以基于 File 的 Cache 了
一、背景
1. 講故事
18年的時候在做純內(nèi)存項目的過程中遇到了這么一個問題,因為一些核心數(shù)據(jù)都是飄在內(nèi)存中,所以內(nèi)存空間對我們來說額外寶貴,但偏偏項目中有些數(shù)據(jù)需要緩存,比如說需要下鉆的報表上的點,基于性能的考慮,不希望采用獨立的緩存中間件,比如 redis, mongodb,畢竟再怎么滴還是要走網(wǎng)絡io,但直接放在本機內(nèi)存中也不現(xiàn)實,那有沒有均衡于 native cache 和 cache server 之間的方案呢?對的,就是 disk cache,畢竟 磁盤IO 的讀寫要遠大于網(wǎng)絡IO,更何況配的是 SSD 呢。
二、尋找解決方案
1. 檢索 github
有了 disk cache 這個大方向就可以去 github 上檢索關鍵詞,看看有沒有類似的中間件,說實話,java的倒不少,比如著名的 guava,ehcache,不僅有cache的簡單操作,還附帶各種統(tǒng)計信息,刷新了對緩存認知的三觀哈,尤其是 ehcache 太????了,堆內(nèi),堆外,磁盤,分布式通通支持,用 C# 寫的好不容易找到一個 disk cache 還不幸是收費的,氣人哈,用 C# 調(diào)用 Java 肯定不現(xiàn)實了哈。
2. 使用sqlite作為 disk cache
既然開源社區(qū)沒什么好的東西,看來只能自己封裝一下了,像 ehcache 那種高階的 diskcache 搞不定,用簡單的 sqlite 作為本機的 diskcahe 還是可以的,接下來試試看。
class DiskCache
{
private static readonly string dbFile = $@"{Environment.CurrentDirectory}\mysqlite1.db";
private static readonly string connectionString = $@"Data Source={dbFile};Version=3";
//過期數(shù)據(jù)監(jiān)測:【一分鐘來一次】
private static Timer timer = new Timer((arg) =>
{
}, null, 1000, 1000 * 60);
static DiskCache()
{
if (!File.Exists(dbFile))
{
var schema = @"CREATE TABLE Cache (
cachekey VARCHAR (1000) PRIMARY KEY NOT NULL,
cachevalue TEXT NOT NULL,
created DATE NOT NULL,
expried DATE NOT NULL
);";
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Execute(schema);
}
}
}
public static void Set<T>(string key, T value, int expiredMinutes)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
var sql = $"delete from Cache where cachekey =@key;" +
$"insert into Cache(cachekey,cachevalue,created,expried) values (@cachekey,@cachevalue,@created,@expried)";
connection.Execute(sql, new
{
key = key,
cachekey = key,
cachevalue = Newtonsoft.Json.JsonConvert.SerializeObject(value),
created = DateTime.Now,
expried = DateTime.Now.AddMinutes(expiredMinutes)
});
}
}
public static T Get<T>(string key)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
var sql = $"select cachevalue from Cache where cachekey=@cachekey and expried > @expried";
var query = connection.QueryFirstOrDefault(sql, new { cachekey = key, expried = DateTime.Now });
var json = JsonConvert.DeserializeObject<T>(query.cachevalue);
return json;
}
}
}
這里有二個注意點:
- 因為是做緩存,所以數(shù)據(jù)庫和表的創(chuàng)建都要通過程序自動化,數(shù)據(jù)庫是否存在判斷 file 文件是否存在即可。
- 過期數(shù)據(jù)的問題,因為我有 expried 字段,這一點可以學習GC思想,使用 Timer 在后臺定期清理。
有了這些基礎之后,原子化的緩存就實現(xiàn)好了,接下來試一下基本的 Get / Set 方法。
圖片
這個方案很好的節(jié)省了我寶貴的內(nèi)存,同時速度又是 networkio 和 native 之間的一個平衡,算是個不錯的解決辦法吧。
三、aspnetcore 的 EasyCaching
EasyCaching 是園子里 @Catcher Wong 的作品 [https://www.cnblogs.com/catcher1994/p/10806607.html],點贊~~~ 看了下提供了很多種 provider,如下圖:
圖片
我想后面肯定還會有更多的 provider 出現(xiàn),如:leveldb,Cassandra,接下來看看這玩意怎么玩。
1. 安裝使用
在 nuget 上 搜一下 EasyCaching.SQLite 安裝即可,接下來就是使用文檔:https://easycaching.readthedocs.io/en/latest/SQLite/#2-config-in-startup-class 如下圖:
圖片
文檔中是采用依賴注入的方式,而我的程序是 console 模式的后端服務,并沒有 ServiceCollection,先模擬著試試看。
static void Main(string[] args)
{
IServiceCollection services = new ServiceCollection();
services.AddEasyCaching(option =>
{
option.UseSQLite(c =>
{
c.DBConfig = new SQLiteDBOptions
{
FileName = "demo.db",
CacheMode = SqliteCacheMode.Default,
OpenMode = SqliteOpenMode.ReadWriteCreate,
};
}, "m1");
});
IServiceProvider serviceProvider = services.BuildServiceProvider();
var factory = serviceProvider.GetService<IEasyCachingProviderFactory>();
var cache = factory.GetCachingProvider("m1");
cache.Set("user", "hello world!", TimeSpan.FromSeconds(20));
var info = cache.Get<string>("user");
Console.WriteLine(info);
}
圖片
接下來用 SQLiteStudio 打開 demo.db 看一下數(shù)據(jù)呈現(xiàn),如下圖:
圖片
可以看到人家的框架比我的多了一個 name 字段,看樣子是給 多個 cache 做隔離用的,不過這里貌似有三個需要優(yōu)化的地方。
- 并不是每一個程序都要使用 依賴注入 的方式 ,提供更便捷的方式初始化就更好了。
- 看了下源碼,并沒有找到可以定期刪除過期數(shù)據(jù)的業(yè)務邏輯。
- 建議提供一些 cache 的統(tǒng)計信息,如命中次數(shù),某一個key最后命中時間等等時分統(tǒng)計圖。