Aerospike 支持在**單次網絡往返、單個事務**中對同一記錄的多個 Bin 執行多種不同操作(讀、寫、增量、追加、前置、Touch),並可選擇性返回操作後的記錄數據。這實現了真正的原子性「讀改寫」模式,極大降低延遲、簡化應用邏輯。本文詳解操作類型、API 用法、三大經典場景代碼模式。
| 操作 | 描述 | 前置條件 |
|---|---|---|
| write | 寫入值到 Bin | 無 |
| read | 讀取 Bin 值 | 無 |
| increment | 對整數 Bin 執行原子增減 | Bin 必須為整數類型 |
| append | 向 Bin 末尾追加數據 | 數據類型必須與 Bin 原類型一致 (bytes/string) |
| prepend | 向 Bin 開頭前置數據 | 數據類型必須與 Bin 原類型一致 (bytes/string) |
| touch | 更新記錄世代號 (Generation),重置 TTL 續租 | 無 |
執行順序規則:所有 **讀操作在非讀操作完成後執行**;非讀操作按應用添加順序執行。
// 1. 初始化操作集合 (預估操作數)
as_operations ops;
as_operations_inita(&ops, 5);
// 2. 添加操作 (按執行順序)
as_operations_add_write_int64(&ops, "bin_name", value);
as_operations_add_incr(&ops, "counter_bin", 1);
as_operations_add_append_raw(&ops, "log_bin", data, len);
as_operations_add_read(&ops, "bin_name"); // 讀操作最後加
// 3. 準備 Key 和 Record 對象 (用於接收讀結果)
as_key key;
as_key_init(&key, "namespace", "set", "key_value");
as_record rec;
as_record_inita(&rec, 3); // 預期讀取 3 個 Bin
// 4. 執行原子操作
as_error err;
if (aerospike_key_operate(&as, &err, NULL, &key, &ops, &rec) != AEROSPIKE_OK) {
// 錯誤處理
}
// 5. 獲取讀取結果
int64_t val = as_record_get_int64(&rec, "bin_name", 0);
// 6. 清理
as_record_destroy(&rec);
as_operations_destroy(&ops);
記錄 Key = URL。Bin:last_updated(int), views(int), addr(bytes), user(bytes), time(bytes)。每次訪問:更新時間、計數器+1、追加 IP/用戶/時間戳 (以 NULL 分隔)。
as_operations_inita(&ops, 5);
as_operations_add_write_int64(&ops, "last_updated", timestamp);
as_operations_add_incr(&ops, "views", 1);
as_operations_add_append_raw(&ops, "addr", (uint8_t*)addr, strlen(addr)+1);
as_operations_add_append_raw(&ops, "user", (uint8_t*)user, strlen(user)+1);
as_operations_add_append_raw(&ops, "time", (uint8_t*)time_str, strlen(time_str)+1);
// 無讀操作,無需準備 rec
aerospike_key_operate(&as, &err, NULL, &key, &ops, NULL);
as_operations_destroy(&ops);
Key = URL,Bin = views。需返回最新計數值。
as_operations_inita(&ops, 2);
as_operations_add_incr(&ops, "views", 1);
as_operations_add_read(&ops, "views"); // 讀操作
as_record_inita(&rec, 1);
aerospike_key_operate(&as, &err, NULL, &key, &ops, &rec);
int64_t current_views = as_record_get_int64(&rec, "views", 0);
as_record_destroy(&rec);
讀取 x,y,z 三個 Bin,同時 Touch 記錄防止過期淘汰。
as_operations_inita(&ops, 4);
as_operations_add_touch(&ops); // Touch 操作
as_operations_add_read(&ops, "x");
as_operations_add_read(&ops, "y");
as_operations_add_read(&ops, "z");
as_record_inita(&rec, 3);
aerospike_key_operate(&as, &err, NULL, &key, &ops, &rec);
// 獲取 x,y,z 值...
as_record_destroy(&rec);
as_operations_inita 第二參數準確預估操作數,避免動態擴容開銷。ERR_BIN_TYPE (類型不匹配)、ERR_RECORD_TOO_BIG、ERR_KEY_NOT_FOUND (視業務決定是否創建)。operate_latency, operate_error_rate, generation 變化率。Aerospike key_operate 多操作原子事務是**高性能、強一致、低延遲**訪問模式的利器。掌握「操作類型語義、執行順序規則、API 調用模板、三大經典場景模式」,即可在計數器、會話狀態、事件溯源、熱點緩存等高併發場景中,用最少代碼實現最強健的業務邏輯。