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

Getting Started with Momento Cache in Rust

If you need to get going quickly with Rust and Momento Cache, this page contains the basic API calls you'll need. Check the Rust SDK examples for complete, working examples including build configuration files.

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

Set up your API key

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

export MOMENTO_API_KEY=<your Momento API key here>

Import libraries and instantiate a CacheClient object

This code sets up the main function, the necessary imports, and the CacheClient instantiation that each of the other functions will need to call.

use momento::cache::configurations;
use momento::{CacheClient, CredentialProvider, MomentoError};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), MomentoError> {
let _cache_client = CacheClient::builder()
.default_ttl(Duration::from_secs(60))
.configuration(configurations::Laptop::latest())
.credential_provider(CredentialProvider::from_env_var(
"MOMENTO_API_KEY".to_string(),
)?)
.build()?;
// ...
Ok(())
}

Create a new cache in Momento Cache

Use this function to create a new cache in your account.

  match cache_client.create_cache(cache_name).await? {
CreateCache::Created => println!("Cache {} created", cache_name),
CreateCache::AlreadyExists => println!("Cache {} already exists", cache_name),
}

List the names of existing caches in your account

A simple list of the names of caches for the account.

  let response = cache_client.list_caches().await?;
println!("Caches: {:#?}", response.caches);

Write an item to a cache

A simple example of doing a set operation. In the client.set call, the TTL it optional. If you did pass it in, this would override the default TTL value set with the client object.

  cache_client.set(cache_name, "key", "value").await?;
println!("Value stored");

Read an item from a cache

This is an example of a simple read operation to get an item from a cache.

  let response = cache_client.get(cache_name, "key").await?;
let _item: String = response.try_into().expect("I stored a string!");

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.