使用键值存储(Key/Value)

由于键值存储是在 JetStream 持久层之上构建的,你可以从你的 JetStream contextarrow-up-right 中获取 KeyValueManager 对象。

键必须与 NATS 主题采用相同格式,即它可以是以点分隔的标记列表(这意味着在监视存储桶时,你可以使用通配符来匹配键的层次结构),并且只能包含有效字符。值可以是任何字节数组。

创建和删除 KV 存储桶

你可以根据需要创建任意数量独立的键值存储实例,称为“存储桶”。存储桶通常是通过管理方式创建、清除或删除的(例如,使用 nats CLI 工具),但也可以使用以下 KeyValueManager 调用之一完成:

// KeyValue will lookup and bind to an existing KeyValue store.
KeyValue(bucket string) (KeyValue, error)
// CreateKeyValue will create a KeyValue store with the following configuration.
CreateKeyValue(cfg *KeyValueConfig) (KeyValue, error)
// DeleteKeyValue will delete this KeyValue store (JetStream stream).
DeleteKeyValue(bucket string) error

Getting

You can do a get to get the current value on a key, or ask to get a specific revision of the value.

// Get returns the latest value for the key.
Get(key string) (entry KeyValueEntry, err error)
// GetRevision returns a specific revision value for the key.
GetRevision(key string, revision uint64) (entry KeyValueEntry, err error)

Putting

The key is always a string, you can simply use Put to store a byte array, or the convenience PutString to put a string. For 'compare and set' functionality you can use Create and Update.

Deleting

You can delete a specific key, or purge the whole key/value bucket.

Getting all the keys

You can get the list of all the keys currently having a value associated using Keys()

Getting the history for a key

The JetStream key/value store has a feature you don't usually find in key/value stores: the ability to keep a history of the values associated with a key (rather than just the current value). The depth of the history is specified when the key/value bucket is created, and the default is a history depth of 1 (i.e. no history).

Watching for changes

Watching a key/value bucket is like subscribing to updates: you provide a callback and you can watch all of the keys in the bucket or specify which specific key(s) you want to be kept updated about.

最后更新于