键值对存储演练
Prerequisite: enabling JetStream
If you are running a local nats-server
stop it and restart it with JetStream enabled using nats-server -js
(if that's not already done)
You can then check that JetStream is enabled by using
If you see the below instead then JetStream is not enabled
Creating a KV bucket
Just like you have to create streams before you can use them, you need to first create a 'KV bucket' using nats kv add <KV Bucket Name>
:
Storing a value
Now that we have a bucket, we can use it to 'put' (store) values at keys:
which should return Value1
Getting a value
Now that we have value stored at key "Key1" we can retrieve that value with a 'get':
Deleting a value
You can always delete a Key/Value entry by using nats kv del my_kv Key1
Watching a K/V Store
A functionality (normally not provided by Key/Value stores) is available with the NATS KV Store is the ability to 'watch' a bucket (or a particular key in that bucket) and receive real-time updates to changes in the store.
For example run nats kv watch my_kv
: this will start a watcher on the bucket we have just created earlier. If you followed this walkthrough the last operation that happened on the key is that it was deleted. Because by default the KV bucket is set with a history size of one (i.e. it keeps only the last change) and the last operation on the bucket was a delete of the value associated with the key "Key1" that is the only thing that get received by the watcher:
Keep that nats kv watch
running and in another window do another 'put'
As soon as that command is run you will see that put event received by the watcher:
Cleaning up
Once you are finished playing, you can easily delete the KV bucket and release the resource associated with it by using:
最后更新于