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

Momento Cache API リファレンス

コントロールAPI

これらのAPIメソッドは、cacheを管理・制御するために使用されます。

Create cache

指定された名前のcacheを作成します。

属性:

名前説明
cacheNameString作成するcacheの名前。
const result = await cacheClient.createCache(cacheName);
if (result instanceof CreateCache.Success) {
console.log(`Cache '${cacheName}' created`);
} else if (result instanceof CreateCache.AlreadyExists) {
console.log(`Cache '${cacheName}' already exists`);
} else if (result instanceof CreateCache.Error) {
throw new Error(
`An error occurred while attempting to create cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

Delete cache

cacheを削除します。

属性:

名前説明
cacheNameString削除するcacheの名前。
const result = await cacheClient.deleteCache(cacheName);
if (result instanceof DeleteCache.Success) {
console.log(`Cache '${cacheName}' deleted`);
} else if (result instanceof DeleteCache.Error) {
throw new Error(
`An error occurred while attempting to delete cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

List caches

すべてのcacheのリストを返します。

名前説明
nextTokenStringcacheのページネーション用の トークンです。
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()}`);
}

Flush cache

cacheの全データをフラッシュします。

属性:

名前説明
cacheNameStringフラッシュするcacheの名前。
const result = await cacheClient.flushCache(cacheName);
if (result instanceof CacheFlush.Success) {
console.log(`Cache '${cacheName}' flushed`);
} else if (result instanceof CacheFlush.Error) {
throw new Error(
`An error occurred while attempting to flush cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

:::ヒント

Delete CacheCreate Cacheの順に使用することでこのプロセスを模倣できますが、FlushCache APIはcacheの設定を保持したまま、データのみを削除します。

:::

データAPI

これらのAPIメソッドは、cache内のデータを直接操作するために使用されます。

Set

指定された生存時間(TTL)秒の値をcacheに設定します。このkeyの値がすでに存在する場合は、新しい値で置き換えられます。

名前説明
cacheNameStringcacheの名前。
key[]Byte値を追加するkey。
value[]Byte格納される値。
ttlSecondsintcache内のアイテムのTTL。
const result = await cacheClient.set(cacheName, '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 '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

SetBatch

複数のキーと値のペアを、指定されたTTL(Time To Live)秒数でキャッシュに設定します。キーの値がすでに存在する場合は、新しい値に置き換えられます。

NameTypeDescription
cacheNameStringキャッシュの名前
items{ String/[]Byte : String/[]Byte }格納されるべきキーと値のマッピング
ttlSecondsintキャッシュにあるアイテムのために生きる時間
const values = new Map<string, string>([
['abc', '123'],
['xyz', '321'],
['123', 'xyz'],
['321', 'abc'],
]);
const result = await cacheClient.setBatch(cacheName, values);
if (result instanceof CacheSetBatch.Success) {
console.log('Keys and values stored successfully');
} else if (result instanceof CacheSetBatch.Error) {
throw new Error(
`An error occurred while attempting to batch set in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
メソッド・レスポンス・オブジェクト
  • Success
  • results(): CacheSet.Response[]
  • Error

Get

指定されたkeyに対して格納されているcache値を取得します。

名前説明
cacheNameStringcacheの名前。
key[]Byte値を取得するために指定するkeyです。
const result = await cacheClient.get(cacheName, '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 '${cacheName}'`);
} else if (result instanceof CacheGet.Error) {
throw new Error(
`An error occurred while attempting to get key 'test-key' from cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

GetBatch

指定したキーに対応するキャッシュ値を取得します。

NameTypeDescription
cacheNameStringキャッシュの名前
keysString[] / Bytes[]値を取得するキーのリスト
const keys = ['abc', 'xyz', '123', '321'];
const result = await cacheClient.getBatch(cacheName, keys);
if (result instanceof CacheGetBatch.Success) {
const values = result.values();
for (const key of keys) {
console.log(`Retrieved value for key '${key}': ${values[key]}`);
}
} else if (result instanceof CacheGetBatch.Error) {
throw new Error(
`An error occurred while attempting to batch get in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
メソッド・レスポンス・オブジェクト
  • Success
  • values(): Record<string, string>
  • results(): CacheGet.Response[]
  • Error

Delete

与えられたkeyに対して格納されているcache値を削除します。

名前説明
cacheNameStringcacheの名前。
key[]Byte値を削除するために指定するkey。
const result = await cacheClient.delete(cacheName, '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 '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

Increment

既存の値がベース10(10進法)の整数を表すUTF-8文字列である場合に限り、フィールドの値を追加 します。もしフィールドが存在しない場合、このメソッドはフィールドの値をインクリメントして設定しま す。

名前説明
cacheNameStringcacheの名前。
fieldString値のインクリメントする場合の対象となるkey。
amountInteger値に加算する量です。正の値、負の値、またはゼロを指定します。デフォルトは1。

:::注記

インクリメントされた値は、-9223372036854775808から9223372036854775807の間、つまり64ビッ ト符号付き整数配列でなければなりません。そうでない場合は、エラーが返されます。

:::

await cacheClient.set(cacheName, 'test-key', '10');
const result = await cacheClient.increment(cacheName, '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 '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

Ping

サーバにpingを送信します。このAPIは、クライアントがサーバに正常に接続できることを確認するた めの接続性のチェックに使用できます。

メソッドのレスポンスオブジェクト
  • Success
  • Error

具体的な情報については、レスポンスオブジェクトを参照してください。

ItemGetType

与えられたkeyに対して、対応するアイテムが存在する場合、その型(SCALAR、DICTIONARY、LISTな ど)を返します。

名前説明
cacheNameStringcacheの名前。
keyString | Byteitemの型が返却されるべきkey。
メソッドのレスポンスオブジェクト
  • Cache hit
  • 型(): enum: SCALAR, DICTIONARY, SET, LIST, SORTED_SET
const result = await cacheClient.itemGetType(cacheName, '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 '${cacheName}'");
} else if (result instanceof CacheItemGetType.Error) {
throw new Error(
`An error occurred while attempting to get the type of key 'test-key' from cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

KeyExists

指定されたkeyがcacheに存在するかどうかをチェックします。

名前説明
cacheNameStringcacheの名前。
keyString | Bytecacheに存在するかどうかをチェックするkey。
メソッドのレスポンスオブジェクト
  • Success
  • exists(): Bool
  • Error

具体的な情報については、レスポンスオブジェクトを参照してください。

const result = await cacheClient.keyExists(cacheName, 'test-key');
if (result instanceof CacheKeyExists.Success) {
console.log("Does 'test-key' exists in the cache?", result.exists());
} else if (result instanceof CacheKeyExists.Error) {
throw new Error(
`An error occurred while attempting to call keyExists on key 'test-key' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

KeysExist

指定されたkey(複数)がcacheに存在するかどうかをチェックします。

名前説明
cacheNameStringcacheの名前。
keysString[] | Byte[]cacheに存在するかどうかをチェックするkey(複数)。
メソッドのレスポンスオブジェクト
  • Success
  • exists(): Bool[]
  • Error

具体的な情報については、レスポンスオブジェクトを参照してください。

const result = await cacheClient.keysExist(cacheName, ['test-key1', 'test-key2']);
if (result instanceof CacheKeysExist.Success) {
console.log("Do 'test-key1' and 'test-key2' exist in the cache?", result.exists());
} else if (result instanceof CacheKeysExist.Error) {
throw new Error(
`An error occurred while attempting to call keysExist on keys 'test-key1' and 'test-key2' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

SetIfNotExists

指定された値を、指定されたkeyを持つcacheのアイテムに関連付けます。

名前説明
cacheNameStringcacheの名前。
keyString | Bytes設定されるkey。
valueString | Bytes格納される値。
ttlSecondsDurationcacheにあるアイテムの生存時間 (TTL)。
メソッドのレスポンスオブジェクト
  • Stored
  • NotStored
  • Error

具体的な情報については、レスポンスオブジェクトを参照してください。

const result = await cacheClient.setIfNotExists(cacheName, '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 '${cacheName}', 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 '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

生存時間(TTL)API

これらのAPIは、すべての型のcacheに適用されます。

UpdateTtl

cacheアイテムのTTLを、指定された値(秒)で上書きします。

名前説明
cacheNameStringcacheの名前。
keyString | Bytes値のTTLを上書きする対象のkey。
ttlDurationcacheで上書きしたいTTLを秒単位で指定します。
resp, err := client.UpdateTtl(ctx, &momento.UpdateTtlRequest{
CacheName: "cache-name",
Key: momento.String("key"),
Ttl: time.Duration(9999),
})
if err != nil {
panic(err)
}
switch resp.(type) {
case *responses.UpdateTtlSet:
log.Printf("Successfully updated TTL for key\n")
case *responses.UpdateTtlMiss:
log.Printf("Key does not exist in cache\n")
}

IncreaseTtl

TTLを増加させる場合のみ、keyのTTL秒数を指定された値に増やします。

  • TTLが5秒で、6秒を指定した場合、新しいTTLは6秒になります。
  • TTLが5秒で、3秒を指定した場合、TTLは増加しません。 | 名前 | 型 | 説明 | | --------- | ------ | ----------------------------------------------- | | cacheName | String | cacheの名前。 | | | key | String | Bytes | 値のTTLを増加させるkeyの指定。 | | ttl | Duration | 増加したいTTLを秒単位で指定します。 |
resp, err := client.IncreaseTtl(ctx, &momento.IncreaseTtlRequest{
CacheName: "cache-name",
Key: momento.String("key"),
Ttl: time.Duration(9999),
})
if err != nil {
panic(err)
}
switch resp.(type) {
case *responses.IncreaseTtlSet:
log.Printf("Successfully increased TTL for key\n")
case *responses.IncreaseTtlMiss:
log.Printf("Key does not exist in cache\n")
}

DecreaseTtl

TTLを減少させる場合のみ、keyのTTL秒数を指定された値に減らします。

  • TTLが5秒で、3秒を指定した場合、新しいTTLは3秒になります。
  • TTLが5秒で、6秒を指定した場合、TTLは減少しません。
名前説明
cacheNameStringcacheの名前。
keyString | Bytes値のTTLを減少させるkeyの指定。
ttlDuration減少させたいTTLを秒単位で指定します。
resp, err := client.DecreaseTtl(ctx, &momento.DecreaseTtlRequest{
CacheName: "cache-name",
Key: momento.String("key"),
Ttl: time.Duration(9999),
})
if err != nil {
panic(err)
}
switch resp.(type) {
case *responses.DecreaseTtlSet:
log.Printf("Successfully decreased TTL for key\n")
case *responses.DecreaseTtlMiss:
log.Printf("Key does not exist in cache\n")
}

ItemGetTtl

与えられたkeyに対して、そのアイテムがcacheから失効するまでの生存時間(TTL)を返します。

名前説明
cacheNameStringcacheの名前。
keyString | Byteアイテムの型を返すkeyの指定。
メソッドのレスポンスオブジェクト
  • Cache hit
  • remainingTtl(): Duration
  • Cache miss
  • Cache error

具体的な情報については、レスポンスオブジェクトを参照してください。

resp, err := client.ItemGetTtl(ctx, &momento.ItemGetTtlRequest{
CacheName: "cache-name",
Key: momento.String("key"),
})
if err != nil {
panic(err)
}
switch r := resp.(type) {
case *responses.ItemGetTtlHit:
log.Printf("TTL for key is %d\n", r.RemainingTtl().Milliseconds())
case *responses.ItemGetTtlMiss:
log.Printf("Key does not exist in cache\n")
}

認証API

これらのAPIは、Momentoの認証トークンやアクセスを管理するために使用されます。

GenerateAuthToken

指定した権限と有効期限を持つ新しいMomento認証トークンを生成します。

名前説明
scopeTokenScope新しいトークンに付与する権限です。あらかじめ構築されたTokenScope オブジェクトは、SDKによって提供されます。
expiresInExpiresInトークンが期限切れになるまでの秒数、またはneverの指定。
メソッドのレスポンスオブジェクト
  • Success
  • authToken: string - the new auth token
  • refreshToken: string - a refresh token that can be used with the RefreshAuthToken API to refresh the token before it expires
  • expiresAt: Timestamp - the timestamp at which the token will expire
  • Error

具体的な情報については、レスポンスオブジェクトを参照してください。

RefreshAuthToken

既存の有効期限内のMomento認証トークンを更新します。元のトークンと同じ権限と有効期限を持つ 新しいトークンを生成します。

名前説明
refreshTokenString最初のGenerateAuthTokenの呼び出しから取得した、現在の認証トー クンのrefreshTokenを指定。
メソッドのレスポンスオブジェクト
  • Success
  • authToken: string - the new auth token
  • refreshToken: string - a refresh token that can be used with the RefreshAuthToken API to refresh the token before it expires
  • expiresAt: Timestamp - the timestamp at which the token will expire
  • Error

具体的な情報については、レスポンスオブジェクトを参照してください。

コレクションデータ型

コレクション型は、ユースケースに応じて、さまざまなタイプの構造を含むことができます。サポートされ ているデータ型は以下の通りです:

  • Dictionaries(辞書型)は、順序のないフィールドと値のペアを格納するために使用されます。
  • Lists(リスト型)は、順序付けられた要素のコレクションで、各要素が挿入された順序でソートされています。
  • Sets(セット型)は、ユニークな要素の文字列による、順序のないコレクションです。
  • Sorted Sets(ソート済みセット型) は、ユニークな要素の順序付きコレクションです。各要素 は、値:スコアのペアを含んでいます。

利用方法についての詳しい情報は、コレクションデータ型をご覧ください。