Skip to main content

Getting Started with Momento Storage in Java

If you need to get going quickly with Java and Momento Storage, 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 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 connect to return a StorageClient object

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

package momento.client.example.doc_examples;

import momento.sdk.PreviewStorageClient;
import momento.sdk.auth.CredentialProvider;
import momento.sdk.config.StorageConfigurations;

public class CheatSheet {
public static void main(String[] args) {
try (final var storageClient =
new PreviewStorageClient(
CredentialProvider.fromEnvVar("MOMENTO_API_KEY"),
StorageConfigurations.Laptop.latest())) {
// ...
}
}
}

Create a new store in Momento Storage

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

final CreateStoreResponse response = storageClient.createStore("test-store").join();
if (response instanceof CreateStoreResponse.Success) {
System.out.println("Store 'test-store' created");
} else if (response instanceof CreateStoreResponse.Error error) {
if (error.getCause() instanceof StoreAlreadyExistsException) {
System.out.println("Store 'test-store' already exists");
} else {
throw new RuntimeException(
"An error occurred while attempting to create store 'test-store': "
+ error.getErrorCode(),
error);
}
}

List the names of existing stores in your account

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

final ListStoresResponse response = storageClient.listStores().join();
if (response instanceof ListStoresResponse.Success success) {
final String stores =
success.getStores().stream().map(StoreInfo::getName).collect(Collectors.joining("\n"));
System.out.println("Stores:\n" + stores);
} else if (response instanceof ListStoresResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to list stores: " + error.getErrorCode(), error);
}

Write an item to a store

A simple example of doing a put operation.

// this example illustrates how to store a String value
final PutResponse response = storageClient.put("test-store", "test-key", "test-value").join();
if (response instanceof PutResponse.Success) {
System.out.println("Key 'test-key' stored successfully");
} else if (response instanceof PutResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to store key 'test-key' in store 'test-store': "
+ error.getErrorCode(),
error);
}

// Momento Storage also supports storing values of type byte[], long, and double:
byte[] bytesValue = "test-byte-array-value".getBytes(StandardCharsets.UTF_8);
storageClient.put("test-store", "test-byte-array-key", bytesValue).join();
storageClient.put("test-store", "test-integer-key", 42L).join();
storageClient.put("test-store", "test-double-key", 42.0).join();

Read an item from a store

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

final GetResponse response = storageClient.get("test-store", "test-key").join();

// simplified style to access the value, if you're confident the value exists and you know the
// type.
// The optionals in this chain will throw exceptions when you call `.get()` if the item did not
// exist in the store, or is another type besides a String
final String value = response.valueWhenFound().get().getString().get();

// Or, you can use pattern-matching for more production-safe code:
if (response instanceof GetResponse.Found found) {
// if you know the value is a String:
String stringValue =
found
.value()
.getString()
.orElseThrow(() -> new RuntimeException("Value was not a String!"));
// if you don't know the type of the value:
switch (found.value().getType()) {
case STRING -> System.out.println("String value: " + found.value().getString().get());
case BYTE_ARRAY -> System.out.println(
"Byte array value: " + found.value().getByteArray().get());
case LONG -> System.out.println("Long value: " + found.value().getLong().get());
case DOUBLE -> System.out.println("Double value: " + found.value().getDouble().get());
}
} else if (response instanceof GetResponse.NotFound) {
System.out.println("Key 'test-key' was not found in store 'test-store'");
} else if (response instanceof GetResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to get key 'test-key' from store 'test-store': "
+ 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.