import ballerina/cache;
import ballerina/io;
import ballerina/runtime;public function main() returns error? {
    cache:Cache cache = new({
        capacity: 10,
        evictionFactor: 0.2,
        defaultMaxAgeInSeconds: 2,
        cleanupIntervalInSeconds: 3
    });
    _ = check cache.put("key1", "value1");
    _ = check cache.put("key2", "value2", 3600);
    if (cache.hasKey("key1")) {
        string value = <string> check cache.get("key1");
        io:println("key1: " + value);
    }
    runtime:sleep(4000);
    string[] keys = cache.keys();
    io:println("keys: [" + keys.toString() + "]");
    int size = cache.size();
    int capacity = cache.capacity();
    _ = check cache.invalidate("key2");
    _ = check cache.invalidateAll();
}

Cache

The ballerina/cache module is provides capability to extend custom cache storage and eviction policies while providing a in-memory storage and LRU eviction policy by default.

import ballerina/cache;
import ballerina/io;
import ballerina/runtime;
public function main() returns error? {
    cache:Cache cache = new({
        capacity: 10,
        evictionFactor: 0.2,
        defaultMaxAgeInSeconds: 2,
        cleanupIntervalInSeconds: 3
    });

This creates a new cache of size 10. The eviction factor is set to 0.2, which means at the time of eviction 10*0.2=2 entries get removed from the cache. The default max age of the cache entry is set to 2 seconds. The cache cleanup task runs every 3 seconds and clears all the expired entries.

    _ = check cache.put("key1", "value1");

Adds a new entry to the cache.

    _ = check cache.put("key2", "value2", 3600);

Adds a new entry to the cache by overriding the default max age.

    if (cache.hasKey("key1")) {

Checks for the cached key availability.

        string value = <string> check cache.get("key1");
        io:println("key1: " + value);
    }

Fetches the cached value.

    runtime:sleep(4000);

This sends the current worker to the sleep mode for 4 seconds. No execution takes place during this period.

During this period, the cache entry with the key ‘key1’ should be removed since the max of it is set to 2 seconds by default. However, the cache entry with the key ‘key2’ should exist in the cache.

    string[] keys = cache.keys();
    io:println("keys: [" + keys.toString() + "]");

Get the keys of the cache entries.

    int size = cache.size();

Get the size of the cache.

    int capacity = cache.capacity();

Get the capacity of the cache.

    _ = check cache.invalidate("key2");

Discard the given cache entry.

    _ = check cache.invalidateAll();
}

Discard all the cache entries of the cache.

# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `ballerina run` command.
$ ballerina run cache.bal
key1: value1
keys: [key2]