-
Notifications
You must be signed in to change notification settings - Fork 220
RawKV Advanced
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 ...
}
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 ...
}
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 ...
}
Feel free to help improving! Minor changes are warmly welcomed. Just simply click edit!
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Contents
- Client-Go Wiki
- Compatibility
- API V2
- Transactional API
- RawKV API
- Configurations
- Utilities