API reference for Momento Cache
Control APIs
These API methods are used to manage and control caches.
Create cache
Creates a cache with the provided name
Attributes:
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache to be created. |
- JavaScript
- Python
- Java
- Go
- C#
- PHP
- Elixir
const result = await cacheClient.createCache('test-cache');
if (result instanceof CreateCache.Success) {
console.log("Cache 'test-cache' created");
} else if (result instanceof CreateCache.AlreadyExists) {
console.log("Cache 'test-cache' already exists");
} else if (result instanceof CreateCache.Error) {
throw new Error(
`An error occurred while attempting to create cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
create_cache_response = await cache_client.create_cache('test-cache')
match create_cache_response:
case CreateCache.Success():
print("Cache 'test-cache' created")
case CreateCache.CacheAlreadyExists():
print("Cache 'test-cache' already exists.")
case CreateCache.Error() as error:
print(f"An error occurred while attempting to create cache 'test-cache': {error.message}")
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);
}
}
_, err := client.CreateCache(ctx, &momento.CreateCacheRequest{
CacheName: "cache-name",
})
if err != nil {
panic(err)
}
var result = await cacheClient.CreateCacheAsync("test-cache");
if (result is CreateCacheResponse.Success)
{
Console.WriteLine("Cache 'test-cache' created");
}
else if (result is CreateCacheResponse.CacheAlreadyExists)
{
Console.WriteLine("Cache 'test-cache' already exists");
}
else if (result is CreateCacheResponse.Error error)
{
throw new Exception($"An error occurred while attempting to create cache 'test-cache': {error.ErrorCode}: {error}");
}
$create_cache_response = $cache_client->createCache("test-cache");
if ($create_cache_response->asSuccess()) {
print("Cache 'test-cache' created\n");
} elseif ($create_cache_response->asAlreadyExists()) {
print("Cache 'test-cache' already exists\n");
} elseif ($err = $create_cache_response->asError()) {
print("An error occurred while attempting to create 'test-cache': {$err->errorCode()} - {$err->message()}\n");
}
case Momento.CacheClient.create_cache(client, "test-cache") do
{:ok, _} ->
IO.puts("Cache 'test-cache' created")
:already_exists ->
:ok
{:error, error} ->
IO.puts(
"An error occurred while attempting to create cache 'test-cache': #{error.error_code}"
)
raise error
end
Delete cache
Deletes a cache
Attributes:
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache to be deleted. |
- JavaScript
- Python
- Java
- C#
- PHP
- Elixir
const result = await cacheClient.deleteCache('test-cache');
if (result instanceof DeleteCache.Success) {
console.log("Cache 'test-cache' deleted");
} else if (result instanceof DeleteCache.Error) {
throw new Error(
`An error occurred while attempting to delete cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
delete_cache_response = await cache_client.delete_cache('test-cache')
match delete_cache_response:
case DeleteCache.Success():
print("Cache 'test-cache' deleted")
case DeleteCache.Error() as error:
raise Exception(f"An error occurred while attempting to delete 'test-cache': {error.message}")
final CacheDeleteResponse response = cacheClient.deleteCache("test-cache").join();
if (response instanceof CacheDeleteResponse.Success) {
System.out.println("Cache 'test-cache' deleted");
} else if (response instanceof CacheDeleteResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to delete cache 'test-cache': "
+ error.getErrorCode(),
error);
}
var result = await cacheClient.DeleteCacheAsync("test-cache");
if (result is DeleteCacheResponse.Success)
{
Console.WriteLine("Cache 'test-cache' deleted");
}
else if (result is DeleteCacheResponse.Error error)
{
throw new Exception($"An error occurred while attempting to delete cache 'test-cache': {error.ErrorCode}: {error}");
}
$delete_cache_response = $cache_client->deleteCache('test-cache');
if ($err = $delete_cache_response->asError()) {
print("An error occurred while attempting to delete 'test-cache': {$err->errorCode()} - {$err->message()}\n");
} else {
print("Cache 'test-cache' deleted\n");
}
case Momento.CacheClient.delete_cache(client, "test-cache") do
{:ok, _} ->
IO.puts("Cache 'test-cache' deleted")
{:error, error} ->
IO.puts(
"An error occurred while attempting to delete cache 'test-cache': #{error.error_code}"
)
raise error
end
List caches
Lists all caches
Name | Type | Description |
---|---|---|
nextToken | String | Token for pagination of caches. |
- JavaScript
- Python
- Java
- Go
- C#
- PHP
- Elixir
const result = await cacheClient.listCaches();
if (result instanceof ListCaches.Success) {
console.log(
`Caches:\n${result
.getCaches()
.map(c => c.getName())
.join('\n')}\n\n`
);
} else if (result instanceof ListCaches.Error) {
throw new Error(`An error occurred while attempting to list caches: ${result.errorCode()}: ${result.toString()}`);
}
print("Listing caches:")
list_caches_response = await cache_client.list_caches()
match list_caches_response:
case ListCaches.Success() as success:
for cache_info in success.caches:
print(f"- {cache_info.name!r}")
case ListCaches.Error() as error:
raise Exception(f"An error occurred while attempting to list caches: {error.message}")
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);
}
resp, err := client.ListCaches(ctx, &momento.ListCachesRequest{})
if err != nil {
panic(err)
}
switch r := resp.(type) {
case *responses.ListCachesSuccess:
log.Printf("Found caches %+v", r.Caches())
}
var result = await cacheClient.ListCachesAsync();
if (result is ListCachesResponse.Success success)
{
Console.WriteLine($"Caches:\n{string.Join("\n", success.Caches.Select(c => c.Name))}\n\n");
}
else if (result is ListCachesResponse.Error error)
{
throw new Exception($"An error occurred while attempting to list caches: {error.ErrorCode}: {error}");
}
$list_caches_response = $cache_client->listCaches();
if ($caches = $list_caches_response->asSuccess()) {
print("Found caches:\n");
foreach ($caches as $cache) {
$cache_name = $cache->name();
print("- $cache_name\n");
}
} elseif ($err = $list_caches_response->asError()) {
print("An error occurred while attempting to list caches: {$err->errorCode()} - {$err->message()}\n");
}
case Momento.CacheClient.list_caches(client) do
{:ok, result} ->
IO.puts("Caches:")
IO.inspect(result.caches)
{:error, error} ->
IO.puts("An error occurred while attempting to list caches: #{error.error_code}")
raise error
end
Flush cache
Flushes all data from a cache
Attributes:
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache to be flushed. |
- JavaScript
- Java
- C#
const result = await cacheClient.flushCache('test-cache');
if (result instanceof CacheFlush.Success) {
console.log("Cache 'test-cache' flushed");
} else if (result instanceof CacheFlush.Error) {
throw new Error(
`An error occurred while attempting to flush cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
final CacheFlushResponse response = cacheClient.flushCache("test-cache").join();
if (response instanceof CacheFlushResponse.Success) {
System.out.println("Cache 'test-cache' flushed");
} else if (response instanceof CacheFlushResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to flush cache 'test-cache': " + error.getErrorCode(),
error);
}
var result = await cacheClient.FlushCacheAsync("test-cache");
if (result is FlushCacheResponse.Success)
{
Console.WriteLine("Cache 'test-cache' flushed");
}
else if (result is FlushCacheResponse.Error error)
{
throw new Exception($"An error occurred while attempting to flush cache 'test-cache': {error.ErrorCode}: {error}");
}
While you could use Delete Cache, then Create Cache to mimic this, the FlushCache API keeps the settings and only deletes the data in the cache.
Data APIs
These API methods are used to directly interact with data in a cache.
Set
Sets the value in cache with a given Time To Live (TTL) seconds. If a value for this key is already present it will be replaced by the new value.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
key | []Byte | The key under which the value is to be added. |
value | []Byte | The value to be stored. |
ttlSeconds | int | Time to Live for the item in Cache. |
- JavaScript
- Python
- Java
- Go
- C#
- PHP
- Elixir
const result = await cacheClient.set('test-cache', 'test-key', 'test-value');
if (result instanceof CacheSet.Success) {
console.log("Key 'test-key' stored successfully");
} else if (result instanceof CacheSet.Error) {
throw new Error(
`An error occurred while attempting to store key 'test-key' in cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
set_response = await cache_client.set('test-cache', 'test-key', 'test-value')
match set_response:
case CacheSet.Success():
print("Key 'test-key' stored successfully")
case CacheSet.Error() as error:
raise Exception(
f"An error occurred while attempting to store key 'test-key' in cache 'test-cache': {error.message}"
)
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);
}
key := uuid.NewString()
value := uuid.NewString()
log.Printf("Setting key: %s, value: %s\n", key, value)
_, err := client.Set(ctx, &momento.SetRequest{
CacheName: "cache-name",
Key: momento.String(key),
Value: momento.String(value),
Ttl: time.Duration(9999),
})
if err != nil {
var momentoErr momento.MomentoError
if errors.As(err, &momentoErr) {
if momentoErr.Code() != momento.TimeoutError {
// this would represent a client-side timeout, and you could fall back to your original data source
} else {
panic(err)
}
}
}
var result = await cacheClient.SetAsync("test-cache", "test-key", "test-value");
if (result is CacheSetResponse.Success)
{
Console.WriteLine("Key 'test-key' stored successfully");
}
else if (result is CacheSetResponse.Error error)
{
throw new Exception($"An error occurred while attempting to store key 'test-key' in cache 'test-cache': {error.ErrorCode}: {error}");
}
$set_response = $cache_client->set("test-cache", "test-key", "test-value");
if ($set_response->asSuccess()) {
print("Key 'test-key' stored successfully\n");
} elseif ($err = $set_response->asError()) {
print("An error occurred while attempting to store 'test-key': {$err->errorCode()} - {$err->message()}\n");
}
case Momento.CacheClient.set(client, "test-cache", "test-key", "test-value") do
{:ok, _} ->
IO.puts("Key 'test-key' stored successfully")
{:error, error} ->
IO.puts(
"An error occurred while attempting to store key 'test-key' in cache 'test-cache': #{error.error_code}"
)
raise error
end
Get
Get the cache value stored for the given key.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
key | []Byte | The key under which the value is to be retrieved. |
- JavaScript
- Python
- Java
- Go
- C#
- PHP
- Elixir
const result = await cacheClient.get('test-cache', 'test-key');
if (result instanceof CacheGet.Hit) {
console.log(`Retrieved value for key 'test-key': ${result.valueString()}`);
} else if (result instanceof CacheGet.Miss) {
console.log("Key 'test-key' was not found in cache 'test-cache'");
} else if (result instanceof CacheGet.Error) {
throw new Error(
`An error occurred while attempting to get key 'test-key' from cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
get_response = await cache_client.get('test-cache', 'test-key')
match get_response:
case CacheGet.Hit() as hit:
print(f"Retrieved value for key 'test-key': {hit.value_string}")
case CacheGet.Miss():
print("Key 'test-key' was not found in cache 'test-cache'")
case CacheGet.Error() as error:
raise Exception(
f"An error occurred while attempting to get key 'test-key' from cache 'test-cache': {error.message}"
)
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);
}
key := uuid.NewString()
resp, err := client.Get(ctx, &momento.GetRequest{
CacheName: "cache-name",
Key: momento.String(key),
})
if err != nil {
panic(err)
}
switch r := resp.(type) {
case *responses.GetHit:
log.Printf("Lookup resulted in cache HIT. value=%s\n", r.ValueString())
case *responses.GetMiss:
log.Printf("Look up did not find a value key=%s", key)
}
var result = await cacheClient.GetAsync("test-cache", "test-key");
if (result is CacheGetResponse.Hit hit)
{
Console.WriteLine($"Retrieved value for key 'test-key': {hit.ValueString}");
}
else if (result is CacheGetResponse.Miss)
{
Console.WriteLine("Key 'test-key' was not found in cache 'test-cache'");
}
else if (result is CacheGetResponse.Error error)
{
throw new Exception($"An error occurred while attempting to get key 'test-key' from cache 'test-cache': {error.ErrorCode}: {error}");
}
$get_response = $cache_client->get("test-cache", "test-key");
if ($hit = $get_response->asHit()) {
print("Retrieved value for key 'test-key': {$hit->valueString()}\n");
} elseif ($get_response->asMiss()) {
print("Key 'test-key' was not found in cache 'test-cache'\n");
} elseif ($err = $get_response->asError()) {
print("An error occurred while attempting to get key 'test-key' from cache 'test-cache': {$err->errorCode()} - {$err->message()}\n");
}
case Momento.CacheClient.get(client, "test-cache", "test-key") do
{:ok, hit} ->
IO.puts("Retrieved value for key 'test-key': #{hit.value}")
:miss ->
IO.puts("Key 'test-key' was not found in cache 'test-cache'")
{:error, error} ->
IO.puts(
"An error occurred while attempting to get key 'test-key' from cache 'test-cache': #{error.error_code}"
)
raise error
end
Delete
Delete the cache value stored for the given key.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
key | []Byte | The key under which the value is to be deleted. |
- JavaScript
- Python
- Java
- Go
- C#
- PHP
- Elixir
const result = await cacheClient.delete('test-cache', 'test-key');
if (result instanceof CacheDelete.Success) {
console.log("Key 'test-key' deleted successfully");
} else if (result instanceof CacheDelete.Error) {
throw new Error(
`An error occurred while attempting to delete key 'test-key' from cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
delete_response = await cache_client.delete('test-cache', 'test-key')
match delete_response:
case CacheDelete.Success():
print("Key 'test-key' deleted successfully")
case CacheDelete.Error() as error:
raise Exception(f"An error occurred while attempting to delete key 'test-key' from cache 'test-cache': {error.message}")
final DeleteResponse response = cacheClient.delete("test-cache", "test-key").join();
if (response instanceof DeleteResponse.Success) {
System.out.println("Key 'test-key' deleted successfully");
} else if (response instanceof DeleteResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to delete key 'test-key' from cache 'test-cache': "
+ error.getErrorCode(),
error);
}
key := uuid.NewString()
_, err := client.Delete(ctx, &momento.DeleteRequest{
CacheName: "cache-name",
Key: momento.String(key),
})
if err != nil {
panic(err)
}
var result = await cacheClient.DeleteAsync("test-cache", "test-key");
if (result is CacheDeleteResponse.Success)
{
Console.WriteLine("Key 'test-key' deleted successfully");
}
else if (result is CacheDeleteResponse.Error error)
{
throw new Exception($"An error occurred while attempting to delete key 'test-key' from cache 'test-cache': {error.ErrorCode}: {error}");
}
$delete_response = $cache_client->delete("test-cache", "test-key");
if ($delete_response->asSuccess()) {
print("Key 'test-key' deleted successfully\n");
} elseif ($err = $delete_response->asError()) {
print("An error occurred while attempting to delete key 'test-key' from cache 'test-cache': {$err->errorCode()} - {$err->message()}\n");
}
case Momento.CacheClient.delete(client, "test-cache", "test-key") do
{:ok, _} ->
IO.puts("Key 'test-key' deleted successfully")
{:error, error} ->
IO.puts(
"An error occurred while attempting to delete key 'test-key' from cache 'test-cache': #{error.error_code}"
)
raise error
end
Increment
Adds to the value of an item, if and only if the existing value is a UTF-8 string representing a base 10 integer. If the item does not exist, this method sets the item's value to the amount to increment by.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
key | String | The key under which the value is to be incremented. |
amount | Integer | The quantity to add to the value. May be positive, negative, or zero. Defaults to 1. |
The resulting incremented value must be between -9223372036854775808 and 9223372036854775807, ie. a signed 64-bit integer. If not, there will be an error response.
- JavaScript
- Java
await cacheClient.set('test-cache', 'test-key', '10');
const result = await cacheClient.increment('test-cache', 'test-key', 1);
if (result instanceof CacheIncrement.Success) {
console.log(`Key 'test-key' incremented successfully. New value in key test-key: ${result.valueNumber()}`);
} else if (result instanceof CacheIncrement.Error) {
throw new Error(
`An error occurred while attempting to increment the value of key 'test-key' from cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
cacheClient.set("test-cache", "test-key", "10").join();
final IncrementResponse response = cacheClient.increment("test-cache", "test-key", 1).join();
if (response instanceof IncrementResponse.Success success) {
System.out.println(
"Key 'test-key' incremented successfully. New value in key test-key: "
+ success.valueNumber());
} else if (response instanceof IncrementResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to increment the value of key 'test-key' from cache 'test-cache': "
+ error.getErrorCode(),
error);
}
Ping
Sends a ping to the server. This API can be used for checking connectivity to confirm that the client can connect to the server successfully.
Method response object
- Success
- Error
See response objects for specific information.
ItemGetType
For a given key, returns the type (SCALAR, DICTIONARY, LIST, etc.) of the corresponding item, if it exists.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
key | String | Byte | Key whose item type should be returned. |
Method response object
- Cache hit
type()
: enum: SCALAR, DICTIONARY, SET, LIST, SORTED_SET
- Cache miss
- Cache error
See response objects for specific information.
- JavaScript
const result = await cacheClient.itemGetType('test-cache', 'test-key');
if (result instanceof CacheItemGetType.Hit) {
console.log(`Item type retrieved successfully: ${ItemType[result.itemType()]}`);
} else if (result instanceof CacheItemGetType.Miss) {
console.log("Key 'test-key' was not found in cache 'test-cache'");
} else if (result instanceof CacheItemGetType.Error) {
throw new Error(
`An error occurred while attempting to get the type of key 'test-key' from cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
KeyExists
Checks if a provided key exists in the cache.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
key | String | Byte | Key which is to be checked for its existence in the cache. |
Method response object
KeysExist
Checks if provided keys exist in the cache.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
keys | String[] | Byte[] | Keys which are to be checked for their existence in the cache. |
Method response object
SetIfNotExists
Associates the provided value to a cache item with a given key.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
key | String | Bytes | The key to be set. |
value | String | Bytes | The value to be stored. |
ttlSeconds | Duration | Time to Live for the item in Cache. |
Method response object
- Stored
- NotStored
- Error
See response objects for specific information.
- JavaScript
- Java
const result = await cacheClient.setIfNotExists('test-cache', 'test-key', 'test-field');
if (result instanceof CacheSetIfNotExists.Stored) {
console.log("Field 'test-field' set in key 'test-key'");
} else if (result instanceof CacheSetIfNotExists.NotStored) {
console.log("Key 'test-key' already exists in cache 'test-cache', so we did not overwrite it");
} else if (result instanceof CacheSetIfNotExists.Error) {
throw new Error(
`An error occurred while attempting to call setIfNotExists for the key 'test-key' in cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
final SetIfNotExistsResponse response =
cacheClient.setIfNotExists("test-cache", "test-key", "test-field").join();
if (response instanceof SetIfNotExistsResponse.Stored) {
System.out.println("Field 'test-field' set in key 'test-key'");
} else if (response instanceof SetIfNotExistsResponse.NotStored) {
System.out.println(
"Key 'test-key' already exists in cache 'test-cache', so we did not overwrite it");
} else if (response instanceof SetIfNotExistsResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to call setIfNotExists for the key 'test-key' in cache 'test-cache': "
+ error.getErrorCode(),
error);
}
Time to Live APIs
These APIs apply across all cache types.
UpdateTtl
Overwrites the TTL of a cache item with the provided value in seconds.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
key | String | Bytes | The key under which the value's TTL is to be updated. |
ttl | Duration | Time to live that you want to update in cache in seconds. |
IncreaseTtl
Increase the TTL seconds for a key to the provided value only if it would increase the TTL.
Examples
- If the TTL is 5 seconds and is increased to 6 seconds, the new TTL will be 6 seconds.
- If the TTL is 5 seconds and is increased to 3 seconds, the TTL will not be increased.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
key | String | Bytes | The key under which the value's TTL is to be increased. |
ttl | Duration | Time to live that you want to increase to. |
DecreaseTtl
Decrease the TTL seconds for a key to the provided value only if it would decrease the TTL.
Examples
- If the TTL is 5 seconds and is decreased to 3 seconds, the new TTL will be 3 seconds.
- If the TTL is 5 seconds and is decreased to 6 seconds, the TTL will not be decreased.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
key | String | Bytes | The key under which the value's TTL is to be decreased. |
ttl | Duration | Time to live that you want to decrease to. |
ItemGetTtl
For a given key, returns the duration of time remaining (Time To Live) before the item expires from the cache.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
key | String | Byte | Key whose item type should be returned. |
Method response object
- Cache hit
remainingTtl()
: Duration
- Cache miss
- Cache error
See response objects for specific information.
Collection data types
Collections may contain different types of structures depending on your use case. Supported data types are:
- Dictionaries are used to store unordered field:value pairs.
- Lists are a collection of ordered elements, sorted in the sequence each element was inserted.
- Sets are an unordered collection of unique elements in string format.
- Sorted Sets are an ordered collection of unique elements. Each element contains a value:score pair.
For more in-depth information on usage, see collection data types.
Current status of API support in SDKs
For the current status of API support in various SDK languages, see the language support page.