使用Aerospike操作命令创建记录

时间:2019-11-25 14:26:37

标签: aerospike

我正在尝试遵循以下代码。出现“找不到密钥”错误。我想知道是否可以使用Aerospike Multi Ops创建记录。

public long incrementSingle(String counterName, long by){

        // Create a key
        Key recordKey = new Key(Constants.NAMESPACE, Constants.SINGLE_SET, counterName);

        // Increment operation
        Bin incrementCounter = new Bin(Constants.SINGLE_COUNTER_BIN, by);

        // https://www.aerospike.com/docs/client/java/usage/kvs/multiops.html#operation-specification
        Record record = asClient.operate(null, recordKey, 
                            Operation.add(incrementCounter), 
                            Operation.get(Constants.SINGLE_COUNTER_BIN));

        return record.getLong(Constants.SINGLE_COUNTER_BIN);
    } 

2 个答案:

答案 0 :(得分:1)

我认为要使add()起作用,记录必须存在之前。测试在计数器箱中创建一个由recordKey引用的记录,该记录具有一些初始值(例如,初始化为0),然后对其进行递增。 add()的Operation API并未具体指出这一点,但我只是在猜测,因为add()首先会读取磁盘上的现有记录,也许找不到它。 (编辑:请参阅下面评论中使用的“写入策略”的进一步确定性测试/说明。)

答案 1 :(得分:1)

我没有发现任何问题。这是一些执行相同操作的Python代码:

# -*- coding: utf-8 -*-
from __future__ import print_function
import aerospike
from aerospike import exception as e
from aerospike_helpers.operations import operations as oh
import sys

config = {"hosts": [("192.168.243.133", 3000)]}
try:
    client = aerospike.client(config).connect()
except e.ClientError as e:
    print("Error: {0} [{1}]".format(e.msg, e.code))
    sys.exit(2)

key = ("test", "demo", "count-this")
print("Nuke the record")
try:
    client.remove(key)
except:
    pass
ops = [oh.increment("counter", 2), oh.read("counter")]
meta = {"ttl": aerospike.TTL_NEVER_EXPIRE}
for i in range(4):
    try:
        k, m, b = client.operate_ordered(key, ops, meta)
        print("Iteration {0}: bin value is {1}".format(i, b))
    except e.RecordError as e:
        print("Error: {0} [{1}]".format(e.msg, e.code))
        sys.exit(4)
client.close()

产生预期的结果

Nuke the record
Iteration 0: bin value is [('counter', 2)]
Iteration 1: bin value is [('counter', 4)]
Iteration 2: bin value is [('counter', 6)]
Iteration 3: bin value is [('counter', 8)]