Newer Version Available
Session Class
Namespace
Usage
Cache Key Format
This table lists the format of the key parameter that some methods in this class take, such as put, get, and contains.
| Key Format | Description |
|---|---|
| namespace.partition.key | Fully qualified key name. |
| key | Refers to a partition marked as default when the namespace.partition prefix is omitted. |
| local.partition.key | Use the local prefix to refer to the org’s namespace when the org doesn’t have a namespace defined. If the org has a namespace defined, the local prefix also refers to that org’s namespace. |
Example
This class is the controller for a sample Visualforce page (shown in the subsequent code sample). The cached values are initially added to the cache by the init() method, which the Visualforce page invokes when it loads through the action attribute. The cache keys don’t contain the namespace.partition prefix. They all refer to a default partition in your org. The Visualforce page expects a partition named myPartition. To run this sample, create a default partition in your org with the name myPartition.
The Visualforce page contains four output components. The first three components call get methods on the controller that return the following values from the cache: a date, data based on the MyData inner class, and a counter. The next output component uses the $Cache.Session global variable to get the cached string value for the key named output. Next, the $Cache.Session global variable is used again in the Visualforce page to iterate over the elements of a cached value of type List. The size of the list is also returned.
The Visualforce page also contains two buttons. The Rerender button invokes the go() method on the controller. This method increases the values of the counter and the custom data in the cache. If you click Rerender, the two counters increase by one each time. The go() method retrieves the values of these counters from the cache, increments their values by one, and stores them again in the cache.
The Remove button deletes the date-time value (with key datetime) from the cache. As a result, the value next to Cached datetime: is cleared on the page.
1public class SessionCacheController {
2
3 // Inner class.
4 // Used as the data type of a cache value.
5 class MyData {
6 public String value { get; set; }
7 public Integer counter { get; set; }
8
9 public MyData(String value) {
10 this.value = value;
11 this.counter = 0;
12 }
13
14 public void inc() {
15 counter++;
16 }
17
18 override public String toString() {
19 return this.value + ':' + this.counter;
20 }
21 }
22
23 // Apex List.
24 // Used as the data type of a cached value.
25 private List<String> numbers =
26 new List<String> { 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE' };
27
28 // Constructor of the controller for the Visualforce page.
29 public SessionCacheController() {
30 }
31
32 // Adds various values to the cache.
33 // This method is called when the Visualforce page loads.
34 public void init() {
35 // All key values are not qualified by the namespace.partition
36 // prefix because they use the default partition.
37
38 // Add counter to the cache with initial value of 0
39 // or increment it if it's already there.
40 if (!Cache.Session.contains('counter')) {
41 Cache.Session.put('counter', 0);
42 } else {
43 Cache.Session.put('counter', getCounter() + 1);
44 }
45
46 // Add the datetime value to the cache only if it's not already there.
47 if (!Cache.Session.contains('datetime')) {
48 DateTime dt = DateTime.now();
49 Cache.Session.put('datetime', dt);
50 }
51
52 // Add the custom data to the cache only if it's not already there.
53 if (!Cache.Session.contains('data')) {
54 Cache.Session.put('data', new MyData('Some custom value'));
55 }
56
57 // Add a list of number to the cache if not already there.
58 if (!Cache.Session.contains('list')) {
59 Cache.Session.put('list', numbers);
60 }
61
62 // Add a string value to the cache if not already there.
63 if (!Cache.Session.contains('output')) {
64 Cache.Session.put('output', 'Cached text value');
65 }
66 }
67
68 // Return counter from the cache.
69 public Integer getCounter() {
70 return (Integer)Cache.Session.get('counter');
71 }
72
73 // Return datetime value from the cache.
74 public String getCachedDatetime() {
75 DateTime dt = (DateTime)Cache.Session.get('datetime');
76 return dt != null ? dt.format() : null;
77 }
78
79 // Return cached value whose type is the inner class MyData.
80 public String getCachedData() {
81 MyData mydata = (MyData)Cache.Session.get('data');
82 return mydata != null ? mydata.toString() : null;
83 }
84
85 // Method invoked by the Rerender button on the Visualforce page.
86 // Updates the values of various cached values.
87 // Increases the values of counter and the MyData counter if those
88 // cache values are still in the cache.
89 public PageReference go() {
90 // Increase the cached counter value or set it to 0
91 // if it's not cached.
92 if (Cache.Session.contains('counter')) {
93 Cache.Session.put('counter', getCounter() + 1);
94 } else {
95 Cache.Session.put('counter', 0);
96 }
97
98 // Get the custom data value from the cache.
99 MyData d = (MyData)Cache.Session.get('data');
100 // Only if the data is already in the cache, update it.
101 if (Cache.Session.contains('data')) {
102 d.inc();
103 Cache.Session.put('data', d);
104 }
105
106 return null;
107 }
108
109 // Method invoked by the Remove button on the Visualforce page.
110 // Removes the datetime cached value from the session cache.
111 public PageReference remove() {
112 Cache.Session.remove('datetime');
113
114 return null;
115 }
116}This is the Visualforce page that corresponds to the SessionCacheController class.
1<apex:page controller="SessionCacheController" action="{!init}">
2
3 <apex:outputPanel id="output">
4 <br/>Cached datetime: <apex:outputText value="{!cachedDatetime}"/>
5 <br/>Cached data: <apex:outputText value="{!cachedData}"/>
6 <br/>Cached counter: <apex:outputText value="{!counter}"/>
7 <br/>Output: <apex:outputText value="{!$Cache.Session.local.myPartition.output}"/>
8 <br/>Repeat: <apex:repeat var="item" value="{!$Cache.Session.local.myPartition.list}">
9 <apex:outputText value="{!item}"/>
10 </apex:repeat>
11 <br/>List size: <apex:outputText value="{!$Cache.Session.local.myPartition.list.size}"/>
12 </apex:outputPanel>
13
14 <br/><br/>
15 <apex:form >
16 <apex:commandButton id="go" action="{!go}" value="Rerender" rerender="output"/>
17 <apex:commandButton id="remove" action="{!remove}" value="Remove datetime Key" rerender="output"/>
18 </apex:form>
19
20</apex:page>This is the output of the page after clicking the Rerender button twice. The counter value could differ in your case if a key named counter was already in the cache before running this sample.
1Cached datetime:8/11/2015 1:58 PM
2Cached data:Some custom value:2
3Cached counter:2
4Output:Cached text value
5Repeat:ONE TWO THREE FOUR FIVE
6List size:5Session Methods
The following are methods for Session. All methods are static.
get(key)
Signature
public static Object get(String key)
Parameters
Return Value
Type: Object
The cached value as a generic object type. Cast the returned value to the appropriate type.
Usage
Because Cache.Session.get() returns an object, we recommend that you cast the returned value to a specific type to facilitate use of the returned value.
1// Get a cached value
2Object obj = Cache.Session.get('ns1.partition1.orderDate');
3// Cast return value to a specific data type
4DateTime dt2 = (DateTime)obj;If a Cache.Session.get() call doesn’t find the referenced key, it returns null.
get(cacheBuilder, key)
Signature
public static Object get(System.Type cacheBuilder, String key)
Parameters
- cacheBuilder
- Type: System.Type
- The Apex class that implements the CacheBuilder interface.
- key
- Type: String
- A case-sensitive string value that, combined with the class name corresponding to the cacheBuilder parameter, uniquely identifies a cached value.
Return Value
Type: Object
The cached value as a generic object type. Cast the returned value to the appropriate type.
Usage
Because Cache.Session.get(cacheBuilder, key) returns an object, cast the returned value to a specific type to facilitate use of the returned value.
1return ((DateTime)Cache.Session.get(DateCache.class, 'datetime')).format();getAvgValueSize()
Signature
public static Long getAvgValueSize()
Return Value
Type: Long
getMaxValueSize()
Signature
public static Long getMaxValueSize()
Return Value
Type: Long
getPartition(partitionName)
Signature
public static cache.SessionPartition getPartition(String partitionName)
Parameters
- partitionName
- Type: String
- A partition name that is qualified by the namespace, for example, namespace.partition.
Return Value
Type: Cache.SessionPartition
Example
After you get the session partition, you can add and retrieve the partition’s cache values.
1// Get partition
2Cache.SessionPartition sessionPart = Cache.Session.getPartition('myNs.myPartition');
3// Retrieve cache value from the partition
4if (sessionPart.contains('BookTitle')) {
5 String cachedTitle = (String)sessionPart.get('BookTitle');
6}
7
8// Add cache value to the partition
9sessionPart.put('OrderDate', Date.today());
10
11// Or use dot notation to call partition methods
12String cachedAuthor = (String)Cache.Session.getPartition('myNs.myPartition').get('BookAuthor');isAvailable()
Signature
public static Boolean isAvailable()
put(key, value)
put(key, value, visibility)
Signature
public static void put(String key, Object value, Cache.Visibility visibility)
Parameters
- key
- Type: String
- A string that uniquely identifies the value to be cached. For information about the format of the key name, see Usage.
- value
- Type: Object
- The value to store in the cache. The cached value must be serializable.
- visibility
- Type: Cache.Visibility
- Indicates whether the cached value is available only to Apex code that is executing in the same namespace or to Apex code executing from any namespace.
Return Value
Type: void
put(key, value, ttlSecs)
Signature
public static void put(String key, Object value, Integer ttlSecs)
Parameters
- key
- Type: String
- A string that uniquely identifies the value to be cached. For information about the format of the key name, see Usage.
- value
- Type: Object
- The value to store in the cache. The cached value must be serializable.
- ttlSecs
- Type: Integer
- The amount of time, in seconds, to keep the cached value in the session cache. The cached values remain in the cache as long as the Salesforce session hasn’t expired. The maximum value is 28,800 seconds or eight hours. The minimum value is 300 seconds or five minutes.
Return Value
Type: void
put(key, value, ttlSecs, visibility, immutable)
Signature
public static void put(String key, Object value, Integer ttlSecs, cache.Visibility visibility, Boolean immutable)
Parameters
- key
- Type: String
- A string that uniquely identifies the value to be cached. For information about the format of the key name, see Usage.
- value
- Type: Object
- The value to store in the cache. The cached value must be serializable.
- ttlSecs
- Type: Integer
- The amount of time, in seconds, to keep the cached value in the session cache. The cached values remain in the cache as long as the Salesforce session hasn’t expired. The maximum value is 28,800 seconds or eight hours. The minimum value is 300 seconds or five minutes.
- visibility
- Type: Cache.Visibility
- Indicates whether the cached value is available only to Apex code that is executing in the same namespace or to Apex code executing from any namespace.
- immutable
- Type: Boolean
- Indicates whether the cached value can be overwritten by another namespace (false) or not (true).
Return Value
Type: void
remove(key)
Signature
public static Boolean remove(String key)
Parameters
remove(cacheBuilder, key)
Signature
public static Boolean remove(System.Type cacheBuilder, String key)
Parameters
- cacheBuilder
- Type: System.Type
- The Apex class that implements the CacheBuilder interface.
- key
- Type: String
- A case-sensitive string value that, combined with the class name corresponding to the cacheBuilder parameter, uniquely identifies a cached value.