メインコンテンツまでスキップ

Getting Started with Momento Topics in Rust

If you need to get going quickly with Rust and Momento Topics, this page contains the basic API calls you'll need. Check the Rust SDK examples for complete, working code samples.

Install the Momento SDK

The Momento SDK is available on crates.io: momento.

ヒント

Visit crates.io to find the latest available version of the SDK.

Install the client library in an existing Rust project:

cargo add momento

Get your Momento API key

You'll need a Momento API key. You can get one from the Momento Web Console. Once you have your token, store it in an environment variable so that the Momento client can consume it:

export MOMENTO_API_KEY=<your api key here>

Note: it is best practice to put the API key into something like AWS Secret Manager or GCP Secret Manager instead of an environment variable for enhanced security, but we are using one here for demo purposes.

Set up a TopicClient

This code creates the TopicClient that you will use to interact with your pub/sub topic.

  let _topic_client = TopicClient::builder()
.configuration(momento::topics::configurations::Laptop::latest())
.credential_provider(CredentialProvider::from_env_var("MOMENTO_API_KEY")?)
.build()?;

Publish a message to a topic

This is an example of publishing a message to a topic called "topic", then catching the return value to check if the publish was successful.

  topic_client
.publish(cache_name, topic_name, "Hello, Momento!")
.await?;
println!("Published message");

Subscribe to a topic

This is an example of subscribing to a topic called "topic". When messages are published to this topic, the code here receives and prints them asynchronously.

  // Make a subscription
let mut subscription = topic_client
.subscribe(cache_name, topic_name)
.await
.expect("subscribe rpc failed");

// Consume the subscription
while let Some(item) = subscription.next().await {
println!("Received subscription item: {item:?}")
}

Running the code

You can find complete, working examples in the Rust SDK GitHub repo examples directory.

備考

Beyond these basic API calls check out the API reference page for more information on the full assortment of Momento API calls.