LevelDB是google實現的非常高效的kv數據庫,多數是和redis比較。這裏記錄下如何使用。
新建項目
Nuget添加類庫
通過反編譯發現運行時是.NET 4.0 這裏我用4.5測試需要選擇64位平臺
代碼
寫數據
db.Put(WriteOptions.Default,”s” ,"a");
測試數據
var db = DB.Open("c:\\works\\mydb", new Options { CreateIfMissing = true });
System.Diagnostics.Stopwatch sp = new System.Diagnostics.Stopwatch();
sp.Reset();
sp.Start();
long mCount = 0;
while (true)
{
db.Put(WriteOptions.Default,mCount.ToString(),"a");
if (System.Threading.Interlocked.Increment(ref mCount) % 10000 == 0)
{
Console.WriteLine("{0} has inserted. time use {1}ms.", mCount, sp.ElapsedMilliseconds);
}
}
結果:
1s寫入1W條,這個和value有關。
查看C盤:
數據很快,但是需要磁盤容量。
也可以封裝使用:
public class LevelDBHelper
{
private static readonly LevelDBHelper _instance=new LevelDBHelper();
private LevelDB.DB levelDB;
private string dbName = "c:\\works\\mydb";
private LevelDBHelper()
{
Options options = new Options()
{
CreateIfMissing = true,
};
this.levelDB = LevelDB.DB.Open(this.dbName, options);
}
static LevelDBHelper()
{
}
public static LevelDBHelper Instance
{
get { return _instance; }
}
//寫數據
public void WriteData(string key, string value)
{
this.levelDB.Put(new WriteOptions(), key, value);
}
//刪除值
public void DelDataWithKey(string key)
{
this.levelDB.Delete(new WriteOptions() { Sync = true }, key);
}
//獲取值
public string GetValueWithKey(string key)
{
var val = this.levelDB.Get(new ReadOptions(), key).ToString();
return val == null ? null : val;
}
//統計數量和大小
public void getDataSize(ref long dataCount, ref long dataSize)
{
dataCount = 0;
dataSize = 0;
Iterator iterator = this.levelDB.NewIterator(new ReadOptions());
iterator.SeekToFirst();
while (iterator.Valid())
{
++dataCount;
byte[] valBytes = Convert.FromBase64String(iterator.Value().ToString());
dataSize += valBytes.LongLength;
iterator.Next();
}
iterator.Dispose();
}
//使用完數據庫以後Dispose
public void closeDB()
{
this.levelDB.Dispose();
}
}