Skip to content

RawKV Advanced

disksing edited this page Dec 14, 2021 · 6 revisions

Advanced RawKV API

CAS (Compare And Swap) support

By using CAS, we can guarantee that the value is written only when the old value is equal to the provided one.

Note: To use CAS, you must set client.SetAtomicForCAS(true) for all the clients before you use them. If there are some clients in the cluster that are not set up correctly, it may break the CAS constraints.

client.SetAtomicForCAS(true)
previousVal, ok, err := client.CompareAndSwap(context.TODO(), []byte("key"), []byte("oldValue"), []byte("newValue"))
if err != nil {
    // ... handle error ...
}
if ok {
    // ... swap success ...
    // ... previous value equals "oldValue"
} else {
    // ... swap failed ...
    // ... previousVal contains the old value ...
}

TTL (Time To Live) support

You can specify the time it survives in seconds when you put the key-value pair. After the time is exceeded, TiKV will automatically clear the corresponding data, or at least ensure that it will return null when queried - as if the data did not exist.

Note that the TTL cleanup depends on the local clock of the tikv-server. It is necessary to ensure the accuracy of the clock by means of NTP etc.

GetKeyTTL can be used to query the TTL of a key. The returned value is the left seconds of the TTL. If the key does not exist, it returns nil. If the key exists but has no TTL, it returns 0.

Note: BatchPut with TTL is only supported by TiKV v5.3.0+. Old versions will ignore TTLs in the request.

err := client.PutWithTTL(context.TODO(), []byte("key"), []byte("value"), 10)
if err != nil {
    // ... handle error ...
}
// ... the key will be deleted after 10 seconds ...

ttl, err := client.GetKeyTTL(context.TODO(), []byte("key"))
if err != nil {
    // ... handle error ...
}
if ttl == nil {
    // ... key does not exist ...
} else if *ttl == 0 {
    // ... key exists but has no TTL ...
} else {
    // ... key exists and has TTL ...
    // ... *ttl is the left seconds of the key ...
}

Delete Range

To avoid consuming a lot of resources for sending keys over the network, rawkv also supports DeleteRange to quickly delete all data in a range.

err := client.DeleteRange(context.Background(), []byte("begin"), []byte("end"))
if err != nil {
    // ... handle error ...
}