首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 使用 BerkeleyDB(二):序列化、IPut 接口與 Set 操作

     編輯:關於C語言

序列化基礎設施


private readonly BinaryFormatter _formatter = new BinaryFormatter();
private readonly MemoryStream _keyStream = new MemoryStream();
private readonly MemoryStream _dataStream = new MemoryStream();

void InitStreams()
{
    _formatter = new BinaryFormatter();
    _keyStream = new MemoryStream();
    _dataStream = new MemoryStream();
}

IPut 接口:統一鍵訪問


public interface IPut { string Key { get; } }

所有存儲實體必須實現,指定作為 BDB 主鍵的屬性。

Set 操作:插入/更新


public bool Set(IPut put)
{
    Reset(); // 重置事務狀態

    _keyStream.Position = 0;
    _formatter.Serialize(_keyStream, put.Key);
    DbEntry key = DbEntry.InOut(_keyStream.GetBuffer(), 0, (int)_keyStream.Position);

    _dataStream.Position = 0;
    _formatter.Serialize(_dataStream, put);
    DbEntry data = DbEntry.InOut(_dataStream.GetBuffer(), 0, (int)_dataStream.Position);

    WriteStatus status = _btree.Put(_txn, ref key, ref data);
    switch (status)
    {
        case WriteStatus.Success: return true;
        case WriteStatus.NotFound:
        case WriteStatus.KeyExist:
        default: return false;
    }
}

流程解析

  1. 重置流位置 → 序列化 Key/Value 到 MemoryStream。
  2. DbEntry.InOut(buffer, offset, count) 包裝有效字節區間。
  3. btree.Put(txn, ref key, ref data) 在事務中寫入。
  4. 根據 WriteStatus 判斷成功/失敗(KeyExist 視為成功語義可自行調整)。

下一篇預告

Get 操作(含 BufferSmall 重試邏輯)、Remove 操作、事務提交與資源釋放。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved