設定
[設定] → プラットフォームキャッシュ
キャッシュの種類
- 組織キャッシュ
組織の誰もが使用できるデータを保存される。 - セッションキャッシュ
個々のユーザセッションに結び付けられたデータが保存される。
キャッシュキー名の形式
下記の形式.
Namespace.Partition.Key
ドルからユーロの通貨換算レートの例:
local.CurrencyCache.DollarToEuroRate
- 組織キャッシュへの保存
Cache.Org.put('local.CurrencyCache.DollarToEuroRate', '0.91');
- デフォルトパーティションである場合は名前空間とパーティション名をSkipできる
組織キャッシュに対するデータの保存と取得
// Get partition Cache.OrgPartition orgPart = Cache.Org.getPartition('local.CurrencyCache'); // Add cache value to the partition. Usually, the value is obtained from a // callout, but hardcoding it in this example for simplicity. orgPart.put('DollarToEuroRate', '0.91'); // Retrieve cache value from the partition String cachedRate = (String)orgPart.get('DollarToEuroRate'); // Check the cache value that the get() call returned. if (cachedRate != null) { // Display this exchange rate } else { // We have a cache miss, so fetch the value from the source. // Call an API to get the exchange rate. }
セッションキャッシュに対するデータの保存と取得
// Get partition Cache.SessionPartition sessionPart = Cache.Session.getPartition('local.CurrencyCache'); // Add cache value to the partition sessionPart.put('FavoriteCurrency', 'JPY'); // Retrieve cache value from the partition String cachedRate = (String)sessionPart.get('FavoriteCurrency');
Challenge
運用時はnullチェック厳しめにやった方が良い。(当たり前...)
public with sharing class BusScheduleCache { private Cache.OrgPartition part; public BusScheduleCache() { // 本当は一旦newしてnullチェックした方が良い this.part = Cache.Org.getPartition('local.BusSchedule'); } public void putSchedule(String busLine, Time[] schedule) { // 本当はpartのnullチェック必須 this.part.put(busLine, schedule); } public Time[] getSchedule(String busLine) { // partのnullチェックも条件に入れた方が良い if((Time[])this.part.get(busLine) != null) { return (Time[])this.part.get(busLine); } else { return new Time[]{Time.newInstance(8, 0, 0, 0), Time.newInstance(17, 0, 0, 0)}; } } }