Skip to main content

Getting Started with Momento Cache in Java

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

Install the Momento SDK

The Momento SDK is available on Maven Central: `software.momento.java/sdk.

tip

Visit Maven Central to find the latest available version of the SDK.

Install the client library in an existing Java project:

Gradle

implementation("software.momento.java:sdk:1.x.x")

Maven

<dependency>
<groupId>software.momento.java</groupId>
<artifactId>sdk</artifactId>
<version>1.x.x</version>
</dependency>

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 token, 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 connect to return 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.

package momento.client.example.doc_examples;

import java.time.Duration;
import momento.sdk.CacheClient;
import momento.sdk.auth.CredentialProvider;
import momento.sdk.config.Configurations;

public class CheatSheet {
public static void main(String[] args) {
try (final CacheClient cacheClient =
CacheClient.create(
CredentialProvider.fromEnvVar("MOMENTO_API_KEY"),
Configurations.Laptop.v1(),
Duration.ofSeconds(60) /* defaultTTL for your cache items*/,
Duration.ofSeconds(10) /* eagerConnectionTimeout, default is 30 seconds */)) {
// ...
}
}
}

Create a new cache in Momento Cache

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

final CacheCreateResponse response = cacheClient.createCache("test-cache").join();
if (response instanceof CacheCreateResponse.Success) {
System.out.println("Cache 'test-cache' created");
} else if (response instanceof CacheCreateResponse.Error error) {
if (error.getCause() instanceof AlreadyExistsException) {
System.out.println("Cache 'test-cache' already exists");
} else {
throw new RuntimeException(
"An error occurred while attempting to create cache 'test-cache': "
+ error.getErrorCode(),
error);
}
}

List the names of existing caches in your account

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

final CacheListResponse response = cacheClient.listCaches().join();
if (response instanceof CacheListResponse.Success success) {
final String caches =
success.getCaches().stream().map(CacheInfo::name).collect(Collectors.joining("\n"));
System.out.println("Caches:\n" + caches);
} else if (response instanceof CacheListResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to list caches: " + error.getErrorCode(), error);
}

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 connection object.

final SetResponse response = cacheClient.set("test-cache", "test-key", "test-value").join();
if (response instanceof SetResponse.Success) {
System.out.println("Key 'test-key' stored successfully");
} else if (response instanceof SetResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to store key 'test-key' in cache 'test-cache': "
+ error.getErrorCode(),
error);
}

Read an item from a cache

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

final GetResponse response = cacheClient.get("test-cache", "test-key").join();
if (response instanceof GetResponse.Hit hit) {
System.out.println("Retrieved value for key 'test-key': " + hit.valueString());
} else if (response instanceof GetResponse.Miss) {
System.out.println("Key 'test-key' was not found in cache 'test-cache'");
} else if (response instanceof GetResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to get key 'test-key' from cache 'test-cache': "
+ error.getErrorCode(),
error);
}

Running the code

You can find complete, working examples in the Java SDK github repo examples directory.

info

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